Pointers and arrays in C

Pointers

Pointers

Getting address of variable with &

variable pointers with & and * in c

int a = 1;
int * b = &a;

\(*p\) assumes \(p\) is pointer and gets what it points at. \(\&p\) assumes \(p\) is value and gets address of \(p\).

\(NULL\) is literal pointer to no valid data. same as \(0\).

pointer of zero doesn’t work, reserved

Dangling pointers

int * p = NULL;
{
	int a = 1;
	p = &a;
}

\(p\) is dangling after because scope ends.

Void pointers

Arrays

Defining arrays

int vals[] = {1, 2, 3, 4, 5};

Can also define empty array:

Accessing values in arrays

The following are the same. Difference is just syntactic sugar.

a[i]
*(a+i)

Array shifting

Relevant for insertion in place.

sizeof()

This function gets the length of an array. It is determined at compile time.

Buffer overflows

Multi-dimensional arrays

The following are the same. The difference is just syntactic sugar.

a[i][j]
??

(Doesn’t this need to know dimensions of all but last one? How does this work if size not known in eg a function?)

Sort

Regular arrays. If want to insert or remove can create new array with new size. Traversal of array is O(1)

array slices etc operations

c increase size of array. automatically creates array twice as big?? how does this work with stack??

size of array unknown at runtime unless provided

arrays if you have array of length 4 and you look at 5 what happens? Does compiler prevent? What about if just have pointer to array?