Vindhya G
Vindhya G

Reputation: 1369

strings in the subscript in c

What is the meaning of the below code? I thought that it is compilation error. But no compilation error occurs.

int main() 
{ 
    const int a=1; 
    printf("%c", ++a["Gyantonic"]); 
}

Output in Linux a is segmentation fault. It gives a compilation error if a[1] is given in place of ++a["Gyantonic"].

How does it work?

Upvotes: 3

Views: 1020

Answers (3)

ouah
ouah

Reputation: 145899

 ++a["Gyantonic"]

is equivalent to:

++(a["Gyantonic"])

which is equivalent to

++("Gyantonic"[a])

equivalent to

++("Gyantonic"[1])

"Gyantonic"[1] yields 'y' and the ++ increments the 'y' stored in the string literal and yields the result. But "Gyantonic" is a string literal and string literals cannot be modified. This is why you get the segmentation fault.

Upvotes: 7

LSerni
LSerni

Reputation: 57418

++a["Gyantonic"]

means that you are trying to increment the a-th (hence, the 1-st, which is not the first but the second, C strings beginning at 0) character of "Gyantonic".

And since "Gyantonic" is a read only constant string, none of its character may be incremented, and you get a segmentation fault.

In gcc with warnings enabled you get:

 warning: increment of read-only location ‘"Gyantonic"[a]’ [enabled by default]

The intended output is apparently "z" (the "y" in Gyantonic incremented by 1). To do this you should write:

    char string[] = "Gyantonic";
    const int a=1;
    printf("%c", ++a[string]);

Note that this is not the same as writing

    char *string = "Gyantonic";

The first version creates an array and initializes (COPIES) in this writeable array the existing, readonly string "Gyantonic". The second version creates a pointer, a label to the existing, readonly string "Gyantonic".

Writing to the writeable copy string[] is allowed; writing to the readonly pointed by *string will segfault.

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375814

In C, the expression x[y] is exactly equal to *(x+y). Since addition is commutative, that means you can also write it as y[x], which is *(y+x), the same thing.

Upvotes: 1

Related Questions