Skip to content

Instantly share code, notes, and snippets.

@akaptur
Created August 3, 2012 22:05
Show Gist options
  • Save akaptur/3251981 to your computer and use it in GitHub Desktop.
Save akaptur/3251981 to your computer and use it in GitHub Desktop.
fun with pointers
# include <stdlib.h>
# include <stdio.h>
int main()
{
int myarray[10] = {100,4,'c','d','e','f','g','h','i','j'};
int *a_goddamn_pointer;
int x, y, z, w;
a_goddamn_pointer = &myarray;
printf("1. %p\n", a_goddamn_pointer); //outputs a memory address
printf("2. %d\n", *a_goddamn_pointer); // outputs '100'
printf("2.5 %p\n", &*a_goddamn_pointer); // same thing as #1!
printf("2.8 %d\n", *&*a_goddamn_pointer); // same thing as #2!
printf("2.9 %d\n", *&myarray); // outputs a memory address
printf("3. %d\n", *(a_goddamn_pointer + 1)); // points to 2nd element of array (outputs '4')
printf("4. %d\n", *a_goddamn_pointer + 1); // adds 1 to 1st element of array (outputs '101')
printf("5. %s\n", &myarray[2]); // outputs 3rd elem of array ('c').
//Note: kind of surprising that this works!
printf("5.5 %p\n", &myarray[2]); // outputs a pointer memory address!
//MORAL: keep an eye on format identifiers!
// printf("6. %s\n", myarray[2]); // This will throw a segfault!
// printf("6.5 %s\n", *myarray[2]); // Segfault
// printf("7. %s\n", *&myarray[2]); // Segfault
printf("7. %s\n", myarray); // outputs 'd'
printf("8. %s\n", &myarray[4]); // outputs 'e'
printf("9. %s\n", myarray); // outputs 'd'
x = &a_goddamn_pointer; // throws a warning (x is not a pointer)
y = a_goddamn_pointer; // throws a warning (y is not a pointer either)
z = *a_goddamn_pointer; // is fine - z will equal 0
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment