tags:

views:

89

answers:

2

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};
+3  A: 

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;
}
Roger Pate
I would use strlcpy() or strncpy_s() if available. strncpy() as a semi-last resort. strcpy() only if you know that it won't overflow and feel like making god cry.
asveikau
Good point. I recommended strcpy because it's standard, he's likely seen it already, and he's guaranteed to have it.
Roger Pate
Thank you, Roger Pate!
Doug
You can do array assignments as part of a structure assignment: `struct a { int b[10]; } a, b = { 0 }; a = b;`
Jonathan Leffler
@asveikau, better use snprintf() instead of strncpy(), this will ensure that your string is nul-terminated.
quinmars
+1  A: 

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

Matt Joiner
Or, slightly more expansively, if the definition of MyStruct contained a char pointer (or, better, a 'const char *'), then the second initializer would work correctly.
Jonathan Leffler