开发者

Initialize a structure with an array in a variable

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 *.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜