[英]Array Initialisation in C using Typedefs
嘗試在C中初始化數組時出現奇怪的錯誤 - 任何人都知道為什么會發生這種情況?
我有一個全局變量:
static my_type foo[6];
在包含的頭文件中,我有:
typedef uint32_t my_type[5];
然后我在與全局變量相同的文件中的函數中嘗試:
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}};
編譯器(GCC4)在'{'token'之前給出錯誤'expected expression'。
任何人都知道出了什么問題以及如何解決它?
干杯!
那不是初始化,那是分配。 初始化必須是一個聲明:
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}};
您無法使用此語法在C89中分配整個數組。 你可以做的是來自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));
}
如果您在C99下:
ISO C99支持復合文字。 復合文字看起來像包含初始值設定項的強制轉換。 它的值是轉換中指定類型的對象,包含初始值設定項中指定的元素; 這是一個左值。 作為擴展,GCC支持C89模式和C ++中的復合文字。
但是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.