xaviersjs
xaviersjs

Reputation: 1737

How do you initialize a struct with struct members?

In C, is there any way to initialize a struct member struct with a variable, or must I initialize with another initialize list? I realize the wording of these questions is terribly confusing, so here's a trivialized code example

#define MAX_VECTOR_SIZE 10
struct ImmutableVectorC
{
    const short vectorSize;
    int vectorElements[MAX_VECTOR_SIZE];
};

struct ImportantVectors
{
    struct ImmutableVectorC vec1;
    struct ImmutableVectorC vec2;
    struct ImmutableVectorC vec3;
    struct ImmutableVectorC vec4;
    struct ImmutableVectorC vec5;
}

Suppose I have these structs defined. I want to initialize an ImportantVectors struct with another struct. Is it possible to do something along these lines?

int main()
{
    struct ImmutableVectorC tempStruct = 
    { 
        .vectorSize = (short)2, 
        .vectorElements = 
        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
    };

    struct ImportantVectors initial = 
    {
        .vec1 = tempStruct,
        .vec2 = tempStruct,
        .vec3 = tempStruct,
        .vec4 = tempStruct,
        .vec5 = tempStruct
    };
}

Visual studio is giving cryptic errors and I'm not sure it it's because these aren't compile-time constants, or some memory management issues, etc.

edit: The error VS gives me is:

error C2440: 'initializing' : cannot convert from 'struct ImmutableVectorC' to 'const short'

Upvotes: 0

Views: 171

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148900

First my MSVC compiler does not really like your code. I have to end all struct element declaration with ; and not , :

struct ImmutableVectorC
{
     short vectorSize;
    int vectorElements[MAX_VECTOR_SIZE];
};

struct ImportantVectors
{
    struct ImmutableVectorC vec1;
    struct ImmutableVectorC vec2;
    struct ImmutableVectorC vec3;
    struct ImmutableVectorC vec4;
    struct ImmutableVectorC vec5;
};

Next the initialization of tempStruct does not allow for the .name= construct and wants instead :

struct ImmutableVectorC tempStruct = 
{ 
    (short)2, 
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};

But the real problem is that my MSVC C compiler does not allow for struct copy in initialization, and insist on having instead :

struct ImportantVectors initial = {
    { 
    (short)2, 
        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
    },
    ...
};

But I could test using clang and gcc, and both accept field name and struct copy on initialization (but definitively want ; in struct field declaration):

struct ImportantVectors initial2 =
{
    .vec1 = tempStruct,
    .vec2 = tempStruct,
    .vec3 = tempStruct,
    .vec4 = tempStruct,
    .vec5 = tempStruct,
};

Upvotes: 1

Related Questions