Search code examples
carraysstructinitializationinitializer-list

Initialize a struct with previous declared array


I have the following situation:

typedef struct A {
    unsigned int a[4];
} A_;

int main() {
    unsigned int b[4] = {1,2,3,4};
    A_ a = {b};
}

This is making me get the following warning:

warning: initialization of 'unsigned int' from 'unsigned int *' makes integer from pointer without a cast

But making this A_ a = {{1,2,3,4}}; is ok. Why?


Solution

  • Standard C does not provide any mechanism to initialize a structure member with an array, except for initializing arrays with string literals.

    Instead, you can initialize the structure with a structure. Assuming the values you want to use are known when the code is written, the latter structure can also be made static const:

    int main(void)
    {
        static const A_ InitialStructure = {{ 1, 2, 3, 4 }};
        A_ a = InitialStructure;
    }