in Programming edited by
974 views
3 votes
3 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);
}
in Programming edited by
by
974 views

1 Answer

6 votes
6 votes
Best answer

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
by

4 Comments

compiler is giving that it is illegal initialization giving for char **ss[]={(s+3),(s+2),(s+1),(s+0)};
But if instead of char *s[] when
I write static char*s[] than it runs properly why is it so???
0
0
Which compiler?
0
0

It is working on Code blocks properly but producing error in Turbo C

0
0
Turbo C is not a standard C compiler, if any standard C compiler produces error you can tell here. Also using Turbo C and similar outdated products will ruin ones career in many ways.
1
1