Pointers

A pointer is just a number to a memory address in the heap/freestore. We can access this memory if we have the adress to it.

C

#include <stdio.h>

int main() {
    int i = 6;
    int *p; // p is a pointer
    p = &i; // Set p to the address of i, not the value
    int *q;
    q = p; // Set q to the value of p which is the address to i
    
    *q = 10; // De-reference q, which means to set i to 10, and hence affecting q and p as well
}

De-reference: assign the address value
Assignment: assign the address

Suppose we have int *p = 123. Which of the following is different
a) *&p - will print the value of the address of p, which is the address of p (same as d)
b) &*p - will print the address of the value of p (same as d)
c) *p - will print the value at the address p
d) p - will print the address p

Error

int *myInt;

myInt = 10;

This is an error, because myInt does not yet point to a valid address.

Error

int *myInt = 10;

This is an error (or, an error when we try to use myInt), because a pointer needs to point to an address of another variable. In this case, you want to use Dynamic Memory Allocation.

Pointer Arithmetic

We can point to the next element in an array by adding 1 to the pointer of the array, which is the first element. Even with non-arrays, you can still add/subtract and compare pointers, you'll just point at something unknown.

Example

The following 2 programs are equivalent

int main() {
    int a[4] = {5, 2, 9, 4};
    int sum = 0;

    for (int *p = a; p < a + 4; p++) {
        sum += *p;
    }
}
int main() {
    int a[4] = {5, 2, 9, 4};
    int sum = 0;
    int *p = &a[0];

    while (p < &a[4]) {
        sum += *p++; // Increment p AFTER use
    }
}

Pointers to Structs

(*t).hour = 18;
t->hour = 18; // Equivanent

C++

There's a special constant in C++11 called nullptr, means it's not pointed to anything. Use this instead of NULL.