Char string within a structure not working

I defined a character string in a structure, but it does not work properly. I get the following error message for line 6:
error: expected ':', ',', ';', '}' or '__attribute__' before '=' token|
What could have gone wrong?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h.>
#include<stdlib.h>

struct test
{
    char str[]="what is wrong with the code?";
    int a, b, c;
}
int main()
{
    struct test d;
    printf("%s", data.str);
    return 0;
}

In C you can't give values to the members in the struct definition like that. You will have to assign the values after you created the object. That also means you'll have to specify the array size explicitly.

1
2
3
4
5
6
7
8
// Create object
struct test d;

// Initialize object
strcpy(d.str, "this should work as long as the array is big enough!");
d.a = 1;
d.b = 2;
d.c = 3;
Last edited on
Topic archived. No new replies allowed.