简体   繁体   中英

Array Initialisation in C using Typedefs

Getting an odd error trying to initialise an array in C - anyone know why this might happen?

I have a global variable:

static my_type foo[6];

And in an included header file, I have:

typedef uint32_t my_type[5];

I then in a function in the same file as the global variable try to do:

foo = {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 6}, {1, 2, 3, 4, 7}, {1, 2, 3, 4, 8}, {1, 2, 3, 4, 9}, {1, 2, 3, 4, 10}};

The compiler (GCC4) gives the error 'expected expression before '{' token'.

Anyone know what's gone wrong and how to fix it?

Cheers!

That's not initialization, that's assignment. Initialization has to be a single statement:

static my_type foo[6] = {{1, 2, 3, 4, 5},
                         {1, 2, 3, 4, 6},
                         {1, 2, 3, 4, 7},
                         {1, 2, 3, 4, 8},
                         {1, 2, 3, 4, 9},
                         {1, 2, 3, 4, 10}};

You cannot assign to a whole array in C89 with this syntax. What you can do is memcpy from a const :

void initialize_foo()
{
    static const my_type init[6] =
                        {{1, 2, 3, 4, 5},
                         {1, 2, 3, 4, 6},
                         {1, 2, 3, 4, 7},
                         {1, 2, 3, 4, 8},
                         {1, 2, 3, 4, 9},
                         {1, 2, 3, 4, 10}};
    assert(sizeof(foo) == sizeof(init));
    memcpy(foo, init, sizeof(foo));
}

If you are under C99:

ISO C99 supports compound literals. A compound literal looks like a cast containing an initializer. Its value is an object of the type specified in the cast, containing the elements specified in the initializer; it is an lvalue. As an extension, GCC supports compound literals in C89 mode and in C++.

But foo must be a pointer

#include <stdio.h>
#include <stdint.h>

typedef uint32_t my_type[5];

int main(void)
{
    int i, j;
    my_type *foo;

    foo = ((my_type[]) {
      {1, 2, 3, 4, 5},
      {1, 2, 3, 4, 6},
      {1, 2, 3, 4, 7},
      {1, 2, 3, 4, 8},
      {1, 2, 3, 4, 9},
      {1, 2, 3, 4, 10}
    });
    for (i = 0; i < 6; i++) {
        for (j = 0; j < 5; j++) {
            printf("%d ", foo[i][j]);
        }
        printf("\n");
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM