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)passedprintfvalue of current character instead of address, printedprintfif pointer; hex values saw character codes of characters of"string"instead of address (notice passingprintfdifferent arguments expected format string undefined behavior, fact produced sensible output accidental); - the second
printfaffected 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
aincremented before or after second argumentprintfevaluated. - using
char *instead ofconst char *pointers string literals deprecated;
Comments
Post a Comment