Created
January 30, 2012 19:09
-
-
Save smonn/1706038 to your computer and use it in GitHub Desktop.
C pointer sample
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> | |
void foo1(int * bar) { | |
// bar is now set to 2 outside this function | |
// scanf works in a similar way | |
// * dereferences bar, without it we would try to assign 2 to a pointer | |
*bar = 2; | |
} | |
void foo2(int bar) { | |
// won't affect bar outside of this function | |
bar = 5; | |
} | |
int main(int argc, const char * argv[]) { | |
int bar = 3; | |
// this function needs a pointer, so we use & to get the pointer to bar | |
foo1(&bar); | |
// won't do anything to bar in this scope | |
foo2(bar); | |
printf("%d", bar); // will print 2 | |
getchar(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment