The screenplay:
// The Tale of Pointers in C: Demos to refer when using pointers in C // License: GPL v3.0 // Author: Forrest Sheng Bao http://fsbao.net Forrest dot His_last_name =aT= gmail.com #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { printf("\n\t Every story has a beginning.\n\n"); int i =10; int* a = &i; printf("\t We have an integer i=%d\n\n", i); printf("\t It is stored in memory address %p.\n\n", a); printf("\t To access the integer, we dereference the pointer: %d. \n\n", *a); printf("\t For strings, it's a different story \n\n"); char *sdring; if (argc > 1) { sdring = argv[1]; printf("\t The first parameter of this shell command is %s\n\n", argv[1]); printf("\t The first character is: %c.\n\n", *argv[1]); printf("\t The second character is: %c.\n\n", *(sdring+1)); printf("\t The string from the 2nd character is %s.\n\n", sdring+1); *(sdring+10) = "Z"; printf("\t You won't see a Z: %c.\n\n", *(sdring+10)); /* printf("\t This will cause a segmentation fault %s", *sdring);*/ } }
The final show
$ gcc pointer.c pointer.c: In function ‘main’: pointer.c:32: warning: assignment makes integer from pointer without a cast $ ./a.out abcdef Every story has a beginning. We have an integer i=10 It is stored in memory address 0xbfe2646c. To access the integer, we can dereference the pointer: 10. For strings, it's a different story The first parameter of this shell command is abcdef The first character is: a. The second character is: b. The string from the 2nd character is bcdef. You won't see a Z: U.
No comments:
Post a Comment