-2

Is it right to say that the null terminating C string is automatically added by the compiler in general?

So in the following example:

char * str = "0124";
printf("%x", str[str[3] - str[2] + str[4]]);

the output is always 32?

Thanks.

rok
  • 9,403
  • 17
  • 70
  • 126

3 Answers3

3

First question: yes

Second question: yes on a ASCII system: you calculate '4' - '2' + '\0' which is in integers: 0x34 - 0x32 + 0 = 2 so you get str[2] which is '2' which is 0x32. '4' - '2' to be 2 is defined in C, but if you ran your code on an EBCDIC system, '2' was 0xf2

Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33
1

Yes, the compiler does add the null terminator. Thus there is 5 bytes of memory allocated to str off the stack.

By the looks of it, with that string literal, (str[3] - str[2] + str[4]) evaluates to (52 - 50 + 0), so you are acessing str[2], which will print 0x32 in hex.

zztops
  • 694
  • 1
  • 5
  • 11
1

The terminating null character is added by the compiler; 6.4.5p6:

6 - In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. [...]

The printf output will be the character code of the 2 character on your system. The characters 0 to 9 are guaranteed to have contiguous codes (5.2.1p3), but not to have any particular value.

ecatmur
  • 152,476
  • 27
  • 293
  • 366