How can we initialize a structure with an array (using its variable)?
This version works well:
MyStruct test = {"hello", 2009};
But this version is bugged:
char str[] = "hello";
MyStruct test =开发者_JAVA百科 {str, 2009};
You cannot assign arrays in C, so unfortunately there's no way to do that directly. You may use strcpy to copy the data, though.
typedef struct {
char name[20];
int year;
} MyStruct;
int main() {
MyStruct a = { "hello", 2009 }; // works
char s[] = "hello";
MyStruct b = { "", 2009 }; // use dummy value
strcpy(b.name, s);
return 0;
}
The definition of MyStruct
should contain a first member of type char const *
.
精彩评论