C Pointer and Reference


 * C program to explain address, pointer, reference, and dereference 
 * You can compile this with 
 * 'g++ pointers_program.c -o pointers' and then call it by typing
 * './pointers' in your shell.

#include <stdio.h>

int main()
    /* A variable name is a reference/link to some memory location. The compiler equals the name that we 
     * give to the variable, "num" in the example below, with an address in memory. When you use the
     * variable ("num") the compiler knows the according reference (the 
     * memory address) and uses the value that is stored under that address.

    int num = 10;
    /* So the label "num" is now connected to a memory address under which the value 10 is stored.
     * e.g. the compiler assigns it the memory address 0x01 (that address is hypothetical) and under 
     * this address the value 10 is stored. 
    printf("the value of num = %i\n", num);
    /* Now, if you don't want the value of what "num" holds (i.e. 10), but the address under which "num" stores 
     * that value, you must explicitly say so by using the reference operator "&". So '&num' translates to
     * 'address of variable num'. 
    printf("address of num = %p\n", &num);

    /* The return value of &num is of type "int*". So, in order to save this address in a variable you must declare
     * a variable of type int*. Which is what we call a pointer. If you had declared a variable of a different type e.g. 
     * float num, then &num would return something of type float*.
    int* aPointer = &num;

    /* Now 'aPointer' holds the address of num. We can see this by printing its value:*/
    printf("value of aPointer = %p\n", aPointer);

    /* So a pointer differs from a normal variable in that its value is a memory address.
     * But as with a normal variable we can get the address of a pointer!
    printf("the address of aPointer = %p\n", &aPointer);

    /* So, we get the value of the pointer, which is an address. We get the address of a pointer
     * which is another address. But how can we also get the value of the address that the pointer is storing?
     * In other words - what does the pointer point to? This is something specific for a pointer and 
     * that differs from a normal variable. If we want to get the value of what the pointer is pointing to,
     * we can use the dereference '*' operator:
    printf("what the value of the pointer, i.e. an address, points to:  %i\n", *aPointer);
      /*summing up: a reference is the address of a variable and when we dereference a pointer we get the value
     * of what the pointer is pointing to.*/

    return 0;

Was this helpful?

0 / 0

Cookie Consent with Real Cookie Banner