Pointers

The concept of pointers simply defines another identifier, declared as a pointer, for an existing object.

 

Pointers consist of a memory address that has been assigned the memory address of the object they are being pointed to.

 

Pointers are declared using an asterisk * between the data type and the identifier. The positioning of the asterisk is down to personal preference of programming style:

 

int * myVar ;

int* myVar ;

int *myVar ;

 

 

Although the actual contents of a pointer consist of a memory address, the data type of a pointer must match the data type of the object it is pointing to. This ensures the compiler allocates the correct amount of memory space for the object being pointed to:

 

int *myInt ; //declares a pointer that will point to an int

char *myChar ; //declares a pointer that will point to a char

float *myFlt ; //declares a pointer that will point to a float

 

The ampersand & 'address of' operator is used to assign the address of an existing object to the pointer object:

 

int myVar ;  //declaration

myVar = 5 ;  //definition

int *myPtr ;  //declaration

myPtr = &myVar ;  //definition

 

As with other variables, a pointer can be initialised at time of declaration:

 

int myVar = 5 ;  //integer declaration & definition

int *myPtr = &myVar ;  //pointer declaration & definition

 

*myPtr is now equivalent to myVar, and the two can be used interchangeably for the same object.

 

The use of the asterisk * indicates that it is the value of the object being pointed to that is being referred to, this concept is know as dereferencing the pointer.

 

Compile & Run:

a: 17, *aPtr: 17
b: 42, *bPtr: 42

 


 

If one were to display the contents of the pointer (without the asterisk), you would only see the address of the object being pointed to.

Leave a Reply