Created
February 3, 2013 09:29
-
-
Save Subsentient/4701051 to your computer and use it in GitHub Desktop.
Pointer basics in C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
/* | |
Pointers to pointers' pointers. GET YOUR HANDS OFF MY POINTER!!! | |
A crappy, cheap code snippet by Subsentient. | |
*/ | |
void main() | |
{ | |
int num = 7; | |
int num2 = 3; | |
int *nump; | |
int *numderp; | |
//Make a pointer to an integer, yet to be defined. | |
int **numpp; | |
//Make a pointer to an integer pointer. Double pointer. | |
nump = # | |
//Give the address of num to the pointer nump, making it act as a second name for num when dereferenced. | |
numpp = &nump; | |
//Pointers have addresses too. Give the address of nump to numpp, making numpp a pointer to nump that points to num. | |
*numpp = &num2; | |
//Dereference numpp with an asterisk, saying "we want to talk to the object pointed to by you, Mr numpp. | |
//Next, with the ampersand, we are saying "nump, now you point to num2." | |
numderp = nump; | |
//This makes our pointer named numderp contain a copy, not just point to, of nump. Dereferencing it would give us num2. | |
printf("Direct object reads as %d\n", num); | |
printf("Pointer to direct object reads as %d\n", *nump); | |
printf("Pointer to the pointer that points to direct object reads as %d\n", **numpp); | |
printf("\"Derp\" pointer reads as %d\n", *numderp); | |
//Double pointer requires double dereferencing to get to the *final* object actually pointed to. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment