C Language | Pointers | Pointers

A pointer stores a memory address. Use the address-of operator to obtain an address and the indirection operator to access the referenced value.

Memory References

Memory is divided into addressable locations. A variable stores its value in one of those locations. Prefix a variable with & to obtain its address.

&variable

Use %p to print an address.

Code 1

#include <stdio.h>

int main() {
 char chVar = 'G';
 int iVar = 10;
 printf("chVar: value = %c, address = %p\n" , chVar , (void *)&chVar);
 printf("iVar: value = %d, address = %p\n" , iVar , (void *)&iVar);
 return 0;
}

Storing Addresses

Declare a pointer with *.

type *variable-name;

For example, int *iPo stores the address of an int. Prefix a pointer with * to access the referenced value. This operation is called dereferencing.

Code 2

#include <stdio.h>

int main() {
 int iVar = 100;
 int *iPo = &iVar;
 printf("iPo = %p, &iVar = %p, *iPo = %d\n" ,
   (void *)iPo , (void *)&iVar , *iPo);
 return 0;
}

Dereferencing also allows assignment through a pointer.

Code 3

#include <stdio.h>

int main() {
 int iVar = 0;
 int *iPo = &iVar;
 *iPo = 100;
 printf("iVar = %d\n" , iVar);
 return 0;
}

Pointers allow a function to modify variables owned by its caller.

Code 4

#include <stdio.h>

void swapInt(int *left , int *right) {
 int temporary = *left;
 *left = *right;
 *right = temporary;
}

int main() {
 int iVar1 = 100 , iVar2 = 1000;
 swapInt(&iVar1 , &iVar2);
 printf("iVar1 = %d, iVar2 = %d\n" , iVar1 , iVar2);
 return 0;
}

Pointer types matter because the compiler uses the referenced type to determine how many bytes to read or write. Assign addresses to compatible pointer types unless a deliberate low-level conversion is required.