Pointer Howto For Beginners
Inhaltsverzeichnis[Verbergen] |
the basics
* ... is used to access the content of a pointer
& ... is used to retrieve the memory-address of a variable or a pointer
this will tell address of a variable:
void main() {
int i=7;
cout << &i;
/* Ausgabe zB 0x00FFAB75... */
return 0;
}
a pointer usually is declared and initialized that way:
[datatype_to_point] *[pointer_name] = NULL;
lets declare a pointer called ptr_int for pointing to an integer:
int *ptr_int = NULL;
a pointer always wants a hardware-address to be set to:
ptr_int = &i;
now we can access the content. here's a whole example:
void main() {
int i = 7;
int *ptr_int = NULL;
ptr_int = &i;
cout << ptr_int << endl; /* output: eg 0x00FFABE5... */
cout << *ptr_int << endl; /* output: 7 */
*ptr_int = 666; /* here we set the value with the pointer */
cout << i; /* output: 666 */
return 0;
}
malloc, sizeof and free
- sizeof (datatype) .......... tells us how many bytes a variable-type requires (sizeof(int) will return 4)
- malloc (size_in_bytes) ... searches for a free space in the heap, reserves it, and returns the hardware-address
- free (pointername) ........ frees the memory again
we combine it like this:
void main() {
double *ptr_double = NULL;
ptr_double = (double*) malloc( sizeof( double ) );
*ptr_double = 789.0;
cout << ptr_double << endl; /* output: 0x00FFABCD... */
cout << *ptr_double << endl; /* output: 789 */
free(ptr_double); /* free memory */
return 0;
}
pointer & structs
lets take an example:
struct robopos {
int x;
int y;
int z;
};
int main() {
robopos *ptr_robopos = NULL;
ptr_robopos = (struct robopos*) malloc(sizeof(struct robopos));
ptr_robopos->x = 7;
ptr_robopos->y = 8;
ptr_robopos->z = ptr_robopos->x + ptr_robopos->y;
cout << ptr_robopos->z << endl;
free(ptr_robopos);
cout << endl;
return 0;
}