← Back to Home

CITS2002 - Lecture 10
Introduction to Pointers - Slides

Pointers

  • A pointer is a variable that stores a memory address
    i.e. it holds the location of a value
  • They help system remember where something is in memory

The & Operator

  • &var → gives memory address of var
int total = 42;
printf("%p\n", (void*)&total); // prints address of total
  • p = &total → stores address of total in pointer p

The * Operator

  • If a pointer stores an address, *p gives the item stored at that address

p → “where” (the address)
*p → “what” (the value at that address)

Arrays and Pointers

  • An array’s name is a pointer to its first element

These are equivalent:

int totals[5];
int *p = &totals[0];
int *q = totals;   // same as above

Pointer Arithmetic

Pointers can move across memory:

  • p++ → move pointer to the next element of its type
    • If p points to an int at address 1000, and sizeof(int)=4, then p++ makes it point to 1004
#define N 5
int totals[N];
int *p = totals;
 
for(int i=0; i<N; i++) {
    *p = i;   // set value
    p++;      // move to next integer
}

Combining * and p++:

  • *p++ → set value pointed at to 0 and move p to next element

Functions and Pointers

  • Pointers let functions change variables outside themselves
void addOne(int *n) {
    *n = *n + 1;   // change the value at the address
}
 
int main() {
    int x = 5;
    addOne(&x);
    printf("%d\n", x);  // prints 6
}

Pointer Functionality in Functions:

  • Used for modifying variables in functions
    • Since normal function parameters are copies
  • Essential for: swapping values, updating arrays, managing dynamic memory

Pointers can be used to give functions direct access to something in memory


CITS2002 - Lecture 12