c - Why isn't the address of consecutive array entries, also consecutive? -


when run

char * = "string"; char * b = a; while (*a != '\0')     printf("%p %c\n", *(a), *(a++)); printf("%p\n", *(b+2)); 

the output looks like

0x73 s 0x74 t 0x72 r 0x69 0x6e n 0x67 g 0x72 

also,how program figure out (b+2) located @ 0x72. thought add 2 starting address of b, in case 0x73.

edit: isn't case of unspecified behaviour. explained in answers, mistakenly passing value address format specifier instead of pointer itself.

try

printf("%p %c\n", (void *)a, *a); a++; 

and rejoice, consecutive elements consecutive!

what wrong in code:

  • when wrote *(a) passed printf value of current character instead of address, printed printf if pointer; hex values saw character codes of characters of "string" instead of address (notice passing printf different arguments expected format string undefined behavior, fact produced sensible output accidental);
  • the second printf affected same error;
  • you'll notice here separated increment in separated statement; haccks pointed out, had another cause of undefined behavior, since function call doesn't introduce sequence points between evaluation of arguments; means it's undefined 1 evaluated first, , whether a incremented before or after second argument printf evaluated.
  • using char * instead of const char * pointers string literals deprecated;

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -