Skip to content

Instantly share code, notes, and snippets.

@saya-rbt
Last active July 24, 2020 16:26
Show Gist options
  • Save saya-rbt/4e7b0c84af60fa78afbabe27b0236d45 to your computer and use it in GitHub Desktop.
Save saya-rbt/4e7b0c84af60fa78afbabe27b0236d45 to your computer and use it in GitHub Desktop.
Small C pointer memo

Small C pointer syntax memo

Code

int a = 5;
int *b = &a;
int **c = &b;
int ***e = &c;

void func(int d)
{
	d++;
}

func(a) // a will stay the same, func will just copy it in d, 
	// increment it and garbage collect it after exiting

Memory layout

Address 0 1 2 3 4
Variable b d a e c
Value 2 6 5 4 0
Content &a 6 5 &c &b

Note: d is garbage collected after exiting func. Addressing is arbitrary and is just given as an example.

Pointer and addresses recap

As a rule of thumb, balance asterisks: when the variable gains an asterisk, the type loses one, and vice-versa. Ampersands add asterisks.

Variable Type
a int
b int*
c int**
e int***
*b int
*c int*
**c int
*e int**
**e int*
***e int
&a int*
&b int**
&c int***
&e int****
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment