Created
June 4, 2014 17:43
-
-
Save jotux/04e09379c02b3db9791a to your computer and use it in GitHub Desktop.
Pointer explanation
This file contains hidden or 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
#define ADDRESS_OF(var) &(var) | |
#define VALUE_AT(var) *(var) | |
#define POINTER_TO(type) type* | |
main() | |
{ | |
int foo[3] = {10,20,30}; | |
POINTER_TO(int) bar = ADDRESS_OF(foo); | |
printf("address of foo : 0x%8x\n",ADDRESS_OF(foo[0])); | |
printf("address of foo + 1: 0x%8x\n",ADDRESS_OF(foo[1])); | |
printf("address of foo + 2: 0x%8x\n",ADDRESS_OF(foo[2])); | |
printf("Notice the distance between each address is %d. The total memory used by foo is %d\n",sizeof(int),sizeof(foo)); | |
printf("value at foo : %d\n",VALUE_AT(foo)); | |
printf("value at foo + 1 : %d\n",VALUE_AT(foo + 1)); | |
printf("value at foo + 2 : %d\n",VALUE_AT(foo + 2)); | |
printf("\nbar holds the address of foo: 0x%8x\n",bar); | |
printf("We can now directly access the data bar references\n"); | |
(VALUE_AT(bar))++; | |
(VALUE_AT(bar + 1))++; | |
(VALUE_AT(bar + 2))++; | |
printf("value at foo : %d\n",VALUE_AT(foo)); | |
printf("value at foo + 1 : %d\n",VALUE_AT(foo + 1)); | |
printf("value at foo + 2 : %d\n",VALUE_AT(foo + 2)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment