Pointers

Location
  1. Courses

    /

  2. Quick C course

    /

  3. Pointers

Variable address

The memory of a computer can be seen as a sequence of bytes. Each of them have an address: The first one has the address 1, the following, 2 and so on.

Each variable has an address too. Its address is the address of its first byte. So, if the addresses of the 4 bytes of a variable are 7, 8, 9 and 10, then, its address is 7.

Retrieving the address of a variable

We can retrieve the address of a variable by putting an ampersand before its name:

&variable;

Pointers

A pointer is a variable that is used to store the address of other variables. When a pointer is storing the address of a variable, it is said to 'point' to it.

A pointer is defined the same way as normal variables, except that there is an asterisk before its name:

int *ptr;

A pointer can only point to variables that are of its type.

We define a variable:

int var = 5;

We make 'ptr' point to it:

ptr = &var;

We can access 'var' through 'ptr' by putting an asterisk before its name:

*ptr = 8;

The variable 'var' now equals 8.

The address zero

As said earlier, the address of the first byte of the memory is 1. Zero is therefore an invalid address. We often make unused pointers point to that address:

float *ptr = 0;

Later on, we can test if the variable points to something or not:

1
2
3
4
5
6
7
8
if(ptr != 0) { // It points to something. } else { // It does not. }

Pointer of pointer

It is possible to define pointers of pointers (Yeah, it sounds strange, but it can be useful). We define them with two asterisks:

float **ptrOfPtr;

Here we define a pointer:

float *ptr;

We define a variable:

float var = 7;

We make the pointer point to the variable:

ptr = &var;

We make the pointer of pointer point to the pointer:

ptrOfPtr = &ptr;

We can access 'ptr' through 'ptrOfPtr', like that:

*ptrOfPtr = &var;

We can access 'var' through 'ptrOfPtr', like that:

**ptrOfPtr = 10;

Note that it is possible to define pointers of pointers of pointers and so on...

Pointers as arguments

If we want to be able to change the value of a variable from a function, it must take, as argument, a pointer to that variable.

Here we define a function that changes the value of the variable pointed by its argument:

void setToFive(int * ptr) { *ptr = 5; }

And we use it:

int var = 24; setToFive(&var); // Now, 'var' equals 5.