[C++] Pointers
#2

Pointers usually is used for dynamic allocation of data, passing argument s of a function by references. For example in C# all classes are declared as Pointers(In C# ref is the alternative of pointer, or the unsafe).

 

 

You want to allocate a number of instances;

An wrong example:

int size= 10;

int b ;

 

a good example would be:

int size = 10;
int *b = new int[size];

 

Passing Generic parameters to a function to return multiple types of data.

void switch(int *a, int *b){
int tmp;
tmp = *a;
*a =*b;
*b = tmp;
}

 

Another example is pointers of functions:

Usually used to get the function address from a dll loaded with Load library, or get a function address of a current function, or create an array of functions:

void (*Menus[])(PLAYER *player) =
{
SaveMenu,
LoadMenu,
OptionsMenu
};

 

Creating Design Patterns(example singlethon).

template
class singleton{
private:
static T* instance;
public:
static T* GetInstance(){
if( instance ==NULL){
instance = new T();
}
return instance;
}
};

 

Simple try to use Pointers when you have low resources and dont want to waste them, create allocating and dealocating bytes in memory(Memory management). Since a pointer is only a label(attaches only to the address in memory).

 

Here is a code that will crash a computer(DOS OPERATING SYSTEM) using pointers:

/* --crashdos.c-- */

void main(){
unsigned char *ptr;
int i;

ptr = (unsigned char *)0x0;
for(i=0;i<1024;i++) {
ptr[i]=0x0;
}
return;
}



Messages In This Thread
[No subject] - by Wizatek - 02-12-2012, 09:07 PM
[No subject] - by someone - 02-12-2012, 10:10 PM
[No subject] - by Wizatek - 02-12-2012, 10:36 PM
[No subject] - by Jackster - 02-12-2012, 10:39 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)