0

When I run

char * a = "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 i
0x6e n
0x67 g
0x72

Also,how does the program figure out that (b+2) is located at 0x72. I thought it would just add 2 to the starting address of b, in this case 0x73.

Edit: This isn't a case of unspecified behaviour. As explained in the answers, I was mistakenly passing the value to the address format specifier instead of the pointer itself.

Ayush Goel
  • 435
  • 6
  • 16

2 Answers2

6

Try

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

and rejoice, consecutive elements are actually consecutive!

What was wrong in your code:

  • when you wrote *(a) you passed to printf the value of the current character instead of its address, which was then printed by printf as if it was a pointer; the hex values you saw are the character codes of the characters of "string" instead of their address (notice that passing to printf different arguments from expected from the format string is undefined behavior, the fact that it produced somewhat sensible output is accidental);
  • the second printf is also affected by the same error;
  • you'll notice that here I also separated the increment in a separated statement; as haccks pointed out, as they originally were you also had another cause of undefined behavior, since a function call doesn't introduce sequence points between the evaluation of its arguments; this means that it's undefined which one is evaluated first, and so whether a is incremented before or after the second argument to printf is evaluated.
  • using char * instead of const char * for pointers to string literals is deprecated;
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
1

You don't print addresses but characters. a is an address, *a is the value (of type char) stored at that address. 0x73 is the ASCII code of lowercase 's' and so on.

If you want to print addresses then your code should look like:

char * a = "string";
char * b = a;
while (*a != '\0') {
    printf("%p %c\n", a, *a));       // address and value (char)
    a ++;
}

Also, printf("%p\n", *(b+2)); prints the value of b[2] which is lowercase 'r' (ASCII code 0x72)

axiac
  • 68,258
  • 9
  • 99
  • 134