Pointers in C

#include <stdio.h>

// We'll show how pointers work in contrast to values with
// 2 functions: `zeroval` and `zeroptr`. `zeroval` has an
// `int` parameter, so arguments will be passed to it by
// value. `zeroval` will get a copy of `ival` distinct
// from the one in the calling function.
void zeroval(int ival) {
    ival = 0;
}

// `zeroptr` in contrast has an `int*` parameter, meaning
// that it takes an `int` pointer. The `*iptr` code in the
// function body then *dereferences* the pointer from its
// memory address to the current value at that address.
// Assigning a value to a dereferenced pointer changes the
// value at the referenced address.
void zeroptr(int *iptr) {
    *iptr = 0;
}

int main() {
    int i = 1;
    printf("initial: %d\n", i);

    zeroval(i);
    printf("zeroval: %d\n", i);

    // The `&i` syntax gives the memory address of `i`,
    // i.e. a pointer to `i`.
    zeroptr(&i);
    printf("zeroptr: %d\n", i);

    // Pointers can be printed too.
    printf("pointer: %p\n", (void*)&i);

    return 0;
}

C supports pointers, allowing you to pass references to values and records within your program.

In this example, we demonstrate how pointers work in contrast to values using two functions: zeroval and zeroptr.

The zeroval function takes an int parameter, so arguments are passed to it by value. This means zeroval receives a copy of the value, distinct from the one in the calling function.

On the other hand, zeroptr takes an int* parameter, which is a pointer to an integer. Inside the function, *iptr dereferences the pointer, allowing us to modify the value at the memory address it points to.

In the main function, we create an integer i and demonstrate the difference between passing by value and passing by reference:

  1. We first print the initial value of i.
  2. We call zeroval(i), which doesn’t change the value of i in main.
  3. We then call zeroptr(&i), passing the address of i. This changes the value of i in main because it has a reference to the memory address of that variable.
  4. Finally, we print the memory address of i using the %p format specifier.

To compile and run this C program:

$ gcc -o pointers pointers.c
$ ./pointers
initial: 1
zeroval: 1
zeroptr: 0
pointer: 0x7ffd5e7e70bc

Note that the actual memory address (pointer value) will likely be different on your system.

This example demonstrates the fundamental concept of pointers in C, which allows for efficient manipulation of data by reference.