C pointers and arrays cheat sheet

August 18th 2015 by Samuel Rossille

For ❤ my wife ❤ who is studying hard at the 42 school, with love ;=)

This aims to provide an easy visual guide to people beginning with C arrays and pointers

Pointers

Everything starts with variables

int i;

i = 42;

A pointer is a variable which contains the address of another variable.

int *p;

p = &i;

The pointer itself is a variable and we can set or change it`s value.

// here, p still points to where i is stored in the memory

p = &j;

// now, p points where j is in the memory. i is unchanged in the process

We can use the pointer to modify the contents of the memory at the address "pointed" by the pointer.

*p = 43;

Arrays

You can see C arrays just as "several" small blocks of adjacent parts of the memory containing the same type of data.

The array is the adress of the first block of data.

So if you have 10 chars next to each other in memory, you can use a pointer pointing to the first of them is an array of chars.

Let's call this pointer s.

It would be declared as this:

char *s;

*s points to the first character.

To access the other character, you can add pointers and integers.

s + 1 points the "one character after the caracter pointed by s", s + 2 points the "two character after the caracter pointed by s", etc...

You can also write things like s = s + 4, or s++, or *(s+i), etc... Anything that adds or subtracts a pointer with an integer is valid.

Array notation

For your convenience, C allow a simple way to write (and understand) "the nth char after the beginning of the array".

s[3] means exactly the same as *(s+3), and should be understood as "the 3rd element of the array" instead of "The char 3rd character in the memory after the character pointed by s"

About length

An array doesn't know about it's length. The code that uses an array has to know how many items are in the array and take care of not messing with the memory outside the array

About strings

Strings are just array of characters that end with \0 to signal the end of the string

Example

Print a string using pointers:

int *s = "Hello";

while(*s != '\n')
    putchar(*s);
    s++; // pointer arithmetics

Print a string using arrays:

int *s = "Hello";

int i = 0;
while(s[i] != '\n')
    putchar(s[i]);
    i++;

So if your code deals with a single value, use pointers.

If your code deals with an array of values, use arrays, to make it explicit in the code.

Please ask if anything is unclear :=)