0

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};
1
  • It would help if you posted the definition of 'typedef struct MyStruct { ... } MyStruct;'. Commented Nov 19, 2009 at 22:59

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

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.
Good point. I recommended strcpy because it's standard, he's likely seen it already, and he's guaranteed to have it.
You can do array assignments as part of a structure assignment: struct a { int b[10]; } a, b = { 0 }; a = b;
@asveikau, better use snprintf() instead of strncpy(), this will ensure that your string is nul-terminated.
1

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.