简体   繁体   English

使用Typedef在C中进行数组初始化

[英]Array Initialisation in C using Typedefs

Getting an odd error trying to initialise an array in C - anyone know why this might happen? 尝试在C中初始化数组时出现奇怪的错误 - 任何人都知道为什么会发生这种情况?

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'. 编译器(GCC4)在'{'token'之前给出错误'expected expression'。

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. 您无法使用此语法在C89中分配整个数组。 What you can do is memcpy from a const : 你可以做的是来自const memcpy

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: 如果您在C99下:

ISO C99 supports compound literals. ISO C99支持复合文字。 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++. 作为扩展,GCC支持C89模式和C ++中的复合文字。

But foo must be a pointer 但是foo必须是一个指针

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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