edited by
1,199 views
4 votes
4 votes

Why is it illegal initialization?

#include<stdio.h>
#include<string.h>
main()
{
    char *s[]={"Lakshya","cquest","brainq","cidol"};
    char **ss[]={(s+3),(s+2),(s+1),(s+0)};
    char ***sss=ss;
    printf("%s",**++sss);
    printf("%s",*--*++sss+3);
    printf("%s",sss[-1][-1]+1);
}
edited by

1 Answer

Best answer
7 votes
7 votes

char *s[] 

Here, s is an array of pointers (as precedence of [] is higher) to char, and so it can accept an array of addresses to characters (char arrays) as initializer list. Here, the size of this array is 4. Let me now explain using the given code snippet. 

 char *s[]={"Lakshya","cquest","brainq","cidol"};
 
 s[0] = W; 
 //where W is the address where "Lakshya" is stored
 similarly,
 s[1] = X, s[2] = Y, s[3] = Z;
 
 char **ss[]={(s+3),(s+2),(s+1),(s+0)};
 ss[0] = &Z, ss[1] = &Y, ss[2] = &X, ss[3] = &W
 
char ***sss=ss; //starting address 
//where &Z,&Y,&X and &W are stored sequentially

printf("%s",**++sss);
//++sss = sss + sizeof(& char ***)
//= sss + sizeof(char **)
//= address where &Y is stored 
//(one address having &X gets incremented)
//**++sss will give Y = "brainq"
    
printf("%s",*--*++sss+3);
//++sss will have address where &X is stored (&ss[2])
//*++sss will give &X
//--*++sss will give &W
//*--*++sss will give W = "Lakshya"
//*--*++sss+3 = "shya"

printf("%s",sss[-1][-1]+1);
//sss[-1] = *(sss-1) =  address where &X is stored - 1
// = address where &Y is stored
// sss[-1][-1] = *(*(sss-1)-1)
// = *(&Y -1) = *&X = X = "cquest"
// sss[-1][-1]+1 = X+1 = "quest"

So, output will be 

brainqshyaquest

PS: C compiler will store the string literals "Lakshya", "cquest", "brainq" and "cidol" at some address locations in the RO data segment as literals are not meant to be modified. Trying to change them via pointers can cause segmentation fault. 

selected by

Related questions

0 votes
0 votes
2 answers
1
vishalmessi asked Dec 11, 2016
4,032 views
#include <stdio.h int main() { int a[][3] = {1, 2, 3, 4, 5, 6}; int (*ptr)[3] = a; printf("%d %d ", (*ptr) , (*ptr) ); ++ptr; printf("%d %d\n", (*ptr) , (*ptr) ); return ...