Skip to content

Instantly share code, notes, and snippets.

@heyimblake
Last active October 19, 2018 06:34
Show Gist options
  • Select an option

  • Save heyimblake/c4b971d6d4e7fdf2bbfeee8ec858de06 to your computer and use it in GitHub Desktop.

Select an option

Save heyimblake/c4b971d6d4e7fdf2bbfeee8ec858de06 to your computer and use it in GitHub Desktop.
What is a Pointer? Compile with "gcc -o demo_pointer demo_pointer.c" and run with "./demo_pointer"
#include <stdio.h>
#include <stdlib.h>
int main() {
// Declare a variable named i
// Initialize i with value of 10.
int i = 10;
printf("i = %d\n", i);
// A pointer is literally just the memory-address
// of whatever it is pointing to.
// We can get the address with &
printf("Address of i = &i = %p\n", (void *) &i);
// Declare an integer-pointer named p
// Initialize p with the address of variable i
// & means "get the address of"
// * means
// - declare as a pointer
// - get the value of what this pointer is pointing to (called dereferencing)
// - or multiply
int *p = &i;
// Notice how we use p without the *
// You only need the * when declaring a pointer variable
// Or when you want to get the value of what the pointer is pointing to
printf("p = &i = %p\n", (void *) p);
// How can we get the value of a pointer?
// Like this!
int j = *p;
printf("j = *p = %d\n", j);
return 0;
}
i = 10
Address of i = &i = 0x7ffe836ad2f0
p = &i = 0x7ffe836ad2f0
j = *p = 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment