T5i
T5i

Reputation: 1530

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 = {str, 2009};

Upvotes: 0

Views: 274

Answers (2)

Matt Joiner
Matt Joiner

Reputation: 118470

The definition of MyStruct should contain a first member of type char const *.

Upvotes: 1

Roger Pate
Roger Pate

Reputation:

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;
}

Upvotes: 3

Related Questions