The code uses "" as an arbitrary address, and ""[1] as that address + 1.
This way this-"" gets you 1-based index into the array.
It assumes the compiler dedfuplicates strings, making the behavior of this program undefined.
Here's how I unpack this: ""[1] is the 0 (termination) byte. The 0 byte is then interpreted as an address -- the nil address.
But what's the use of asking for the address of the null terminator? Where is that stored exactly?
Now the first character of that char array is found here: ""[0]
The second character is found here: ""[1]
So the address of the second character is found here: &""[1]
But as the string was represented by one byte char array that second address is past the end of the string.
So it's actually an undefined address.
#include <stdio.h>
#include <string.h>
struct a_struct {
char a[1];
char b[2];
a_struct() {
strcpy(a, "");
strcpy(b, "b");
}
} x;
int main() {
printf("before:\n");
printf("a : '%s'\n", x.a);
printf("b : '%s'\n", x.b);
char *c = &1[x.a];
*c = 'c';
printf("after:\n");
printf("a : '%s'\n", x.a);
printf("b : '%s'\n", x.b); //b is now corrupt
}
Compile and running this code: C:\temp>g++ test.cpp
C:\temp>a.exe
before:
a : ''
b : 'b'
after:
a : ''
b : 'c'Its address is taken there with &, which yields a const char*. The (char *) cast is only there to cast away const.