Skip to content

Instantly share code, notes, and snippets.

@smonn
Created January 30, 2012 19:09
Show Gist options
  • Save smonn/1706038 to your computer and use it in GitHub Desktop.
Save smonn/1706038 to your computer and use it in GitHub Desktop.
C pointer sample
#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