c - initializing array of structure with array elements in it -
#include <stdio.h> int main() { typedef struct s { int a; int b[5]; char c[2]; }st; st vs[1]; vs[0] = {1,{1,2,3,4,5},{'c','d'}}; printf("%d:a\n",vs[1].a); printf("%d:b[0]\t %d:b[4]\n",vs[0].b[0],vs[0].b[4]); printf("%c:c[0]\t %c:c[1]\n",vs[0].c[0],vs[0].c[1]); return 0; }
why doesn't work?
on
gcc -o main *.c
i error
main.c: in function 'main': main.c:15:12: error: expected expression before '{' token vs[0] ={1,{1,2,3,4,5},{'c','d'}};
but if have this:
#include <stdio.h> int main() { typedef struct s { int a; int b[5]; char c[2]; }st; st vs[] = { {1,{1,2,3,4,5},{'c','d'}} }; printf("%d:a\n",vs[0].a); printf("%d:b[0]\t %d:b[4]\n",vs[0].b[0],vs[0].b[4]); printf("%c:c[0]\t %c:c[1]\n",vs[0].c[0],vs[0].c[1]); return 0; }
it works. logic in this.
how can make work using st vs[1] method?
initialization when declare variable , provide initial values part of declaration. example legal:
st vs[1] = { {1,{1,2,3,4,5},{'c','d'}} };
your code attempting assignment. assignment when existing variable has value assigned it. reason code doesn't work {1,{1,2,3,4,5},{'c','d'}}
isn't value.
in statement (not declaration), each expression must readable compiler on own merit, , more complicated statement made of various expressions joined operators. compiler doesn't know {1,{1,2,3,4,5},{'c','d'}}
- @ stage has no idea that supposed st
.
since c99 there new language construct can use here, called compound literal:
vs[0] = (const st){1,{1,2,3,4,5},{'c','d'}};
note not cast operator being applied sort of braced expression; single syntactic construct (typename){ initializers }
.
my use of const
micro-optimization, may compiler store literal in read-only block of executable , allow constant folding.
Comments
Post a Comment