Saturday 15 June 2013

c - initializing char array in main vs in a struct -



c - initializing char array in main vs in a struct -

im attempting initialize array of chars

if in main works fine

char arr1[20] = "initial"; printf("%s", arr1);

but if seek anywhere else such in struct, seek utilize in main function like

struct foo { char arr1[20] = "initial"; } int main(void) { struct foo foobar; printf("%s", foobar.arr1); }

or

struct foo { char arr1[20]; } int main(void) { struct foo foobar; foobar.arr1 = "initial"; printf("%s", foobar.arr1); }

i start getting errors. why 1 work , other doesn't?

you mixing struct definition initialization of variable.

the struct definition says types create struct , names are, e.g.:

struct foo { char arr1[20]; };

says "struct foo type we've defined consists of array[20] of char". there no actual variables of type yet.

then can declare , initialize instances of type, in similar way how declare , initialize arr1 in first example:

struct foo foobar = { "initial" };

c arrays string struct char

No comments:

Post a Comment