c - struct intitialization notation not working with heap allocated storage -
with gcc (gcc) 4.4.6 , try compile program -
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int main(int argc, char *argv[]) 5 { 6 7 struct b { 8 int i; 9 char ch; 10 }; 11 12 struct b *ptr; 13 14 ptr = (struct b*) calloc(1, sizeof(struct b)); 15 16 *ptr = { 17 .i = 10, 18 .ch = 'c', 19 }; 20 21 printf("%d,%c\n", ptr->i, ptr->ch); 22 23 return 0; 24 } 25 $ make gcc -g -wall -o test test.c test.c: in function ‘main’: test.c:16: error: expected expression before ‘{’ token make: *** [test] error 1
*ptr = { .i = 10, .ch = 'c', };
this usage called designated initializer, name implies, it's used initialize struct or arrays, trying assigning.
the correct usage of designated initializer:
strcut b foo = {.i = 10, .ch = 'c'};
to assign struct, still need use:
ptr->i = 10; ptr->ch = 'c';
edit: or can use compound literal in @andrey t's answer:
*ptr = (struct b) { .i = 10, .ch = 'c', };
Comments
Post a Comment