Pointers

Pointers are variables that contain the memory address of the variable/object they point to.

 

All variables exist within a location in memory. This memory location is normally expressed as a hexadecimal number, such as: 22fd6c

 

The value of the memory location can be accessed by using the ampersand & 'address of' operator:

e.g.

printf("The hex address of myVar is %p n", &myVar) ;

 

Pointers are declared by providing the data type * and identifier:

int *myVar ;

int* myVar ;

int * myVar ;

 

All of the above are equivalent. The positioning of the * is down to programming style.

 

Pointers must be declared with the matching data type for the object they point to, i.e. a pointer to an int must be an int pointer, a pointer to a char must be a char pointer:

 

int *myInt ;  //pointer to an int

char *myChar ;  //pointer to a char

float *myFloat ;  //pointer to a float

 

This is important because it tells the compiler how much memory to allocate for operations on the item being pointed at, e.g. dereferencing an int should read 4 bytes from where the address it is pointing to, whereas a char pointer should read just the 1 byte (for the char data type) from the address it is pointing to.

 

The content of the variable being pointed to, is accessed using the * 'dereferencing' operator.

& Address of Operator
* Dereferencing Operator

A pointer is defined by assigning the address of the target variable to the pointer:

 

int *p_myVar = &myVar ;

 

*p_myVar can now be used as if one were directly referring to myVar itself.

 

The contents of myVar can now be changed by assigning a new value either directly or via the pointer *p_myVar

 

Compile & run:

Memory address of myVar is: 000000000022FD6C
Contents of myVar is: 5
Memory address of the pointer p_myVar is: 000000000022FD60
Contents being pointed to by p_myVar is: 5 

Memory address of myVar is: 000000000022FD6C
Contents of myVar is: 42
Memory address of the pointer p_myVar is: 000000000022FD60
Contents being pointed to by p_myVar is: 42

Memory address of myVar is: 000000000022FD6C
Contents of myVar is: 17
Memory address of the pointer p_myVar is: 000000000022FD60
Contents being pointed to by p_myVar is: 17

 


Useful to remember:   *(&x) == x ;

Leave a Reply