21

I have a C struct defined as follows:

struct Guest {
   int age;
   char name[20];
};

When I created a Guest variable and initialized it using the following:

int guest_age = 30;
char guest_name[20] = "Mike";
struct Guest mike = {guest_age, guest_name};

I got the error about the second parameter initialization which tells me that guest_name cannot be used to initialize member variable char name[20].

I could do this to initialize all:

struct Guest mike = {guest_age, "Mike"};

But this is not I want. I want to initialize all fields by variables. How to do this in C?

4
  • 2
    You can't copy arrays. Use std::string.
    – chris
    Sep 23, 2013 at 19:16
  • 1
    I know I can use std::string. But what if I want to stick with C-style char arrays?
    – tonga
    Sep 23, 2013 at 19:17
  • 5
    You said C or C++. Now you say C.
    – chris
    Sep 23, 2013 at 19:17
  • I should make it clear. I want to do it in C char array. Have edited my question. Is it possible?
    – tonga
    Sep 23, 2013 at 19:19

4 Answers 4

29

mike.name is 20 bytes of reserved memory inside the struct. guest_name is a pointer to another memory location. By trying to assign guest_name to the struct's member you try something impossible.

If you have to copy data into the struct you have to use memcpy and friends. In this case you need to handle the \0 terminator.

memcpy(mike.name, guest_name, 20);
mike.name[19] = 0; // ensure termination

If you have \0 terminated strings you can also use strcpy, but since the name's size is 20, I'd suggest strncpy.

strncpy(mike.name, guest_name, 19);
mike.name[19] = 0; // ensure termination
2
  • So this way, I can't initialize other members of this struct using the form Guest mike = {...}. I have to use mike.age = ...,; mike.id=...; memcpy(mike.name, guest_name, 20); if I have more fields.
    – tonga
    Sep 23, 2013 at 19:28
  • If you don't know the string in advance (at compile time), yes.
    – Scolytus
    Sep 23, 2013 at 19:28
6

mike.name is a character array. You can't copy arrays by just using the = operator.

Instead, you'll need to use strncpy or something similar to copy the data.

int guest_age = 30;
char guest_name[20] = "Mike";
struct Guest mike = { guest_age };
strncpy(mike.name, guest_name, sizeof(mike.name) - 1);

You've tagged this question as C++, so I'd like to point out that in that case you should almost always use std::string in preference to char[].

3
  • Thanks. So it is impossible to use C struct initialization to initialize char array members in declaration of a struct, right?
    – tonga
    Sep 23, 2013 at 19:23
  • You need to add null terminator when using strncpy, generally speaking.
    – M.M
    Sep 5, 2016 at 3:47
  • In this example I initialized the struct with the bracket notation which zeroes everything past the specified member. There was a related off-by-one error in the strncpy call, however, as well as some typos I'm surprised nobody's harped on. ;) thanks Sep 6, 2016 at 18:29
0

Actually you can statically initialise this struct:

struct Guest {
   int age;
   char name[20];
};

Guest guest = { 30, {'M','i','k','e','\0'}};

Each element of the array must be set explictly and this cannot be done using c-strings. If the struct is defined with a char* name then we can do this:

struct Guest {
   int age;
   char* name;
};

Guest guest = { 30, "Mike"};
-2

You can statically allocate a struct with a fixed char[] array in C. For example, gcc allows the following:

#include <stdio.h>

typedef struct {
    int num;
    char str[];
} test;

int main(void) {
    static test x={.num=sizeof("hello"),.str="hello"};

    printf("sizeof=%zu num=%d str=%s\n",sizeof(x),x.num,x.str);
    return 0;
}

And it does the right thing (though beware of the sizeof(x): it returns 4 on my machine; not the length of the total statically allocated memory).

This does not work for structs allocated from the stack, as you might suspect.

4
  • (1) I don't believe GCC is so broken as not to return 6 for sizeof("hello") — but maybe you're referring to sizeof(x), in which case 4 is the correct answer. (2) This is called a flexible array member in a structure. (3) The initialization is a GCC extension, though you have to invoke -pedantic to get it to 'fess up: initialization of a flexible array member [-Werror=pedantic] at static test x={.num=sizeof("hello"),.str="hello"}; — compiler options gcc -O3 -g -std=c11 -Wall -Wextra -Werror -pedantic xx37.c. I'm using GCC 6.1.0 on Mac OS X 10.11.6. Sep 5, 2016 at 3:33
  • @JonathanLeffler does this extension also extend the allocated space to allow the initializer to fit?
    – M.M
    Sep 5, 2016 at 3:46
  • @M.M: I'm not sure, but I think so. I don't read x86_64 assembler well, but the output of size xx37.o (where xx37.c contains a copy of the code in this answer) gives a data section of size 10, which corresponds to the size that x should be if it was allocated as a single unit (which is how a FAM must be handled). So, I infer that GCC does the job correctly (not a big surprise given that it does it at all), but I'm willing to be shown that I'm wrong on this. Sep 5, 2016 at 3:55
  • While it is true that this idiom is a gcc extension [1], I don't see anything forbidding it in ISO C99 [2]. [1] gcc.gnu.org/onlinedocs/gcc-4.3.5/gcc/Zero-Length.html [2] ISO/IEC 9899 section 6.7.8 paragraphs 20, 22. Paragraph 31 is also worth a glance if you want to brush up on [].
    – Daniel
    Sep 6, 2016 at 4:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.