简体   繁体   English

在一行中初始化一个struct数组? (在C中)

[英]Initializing an array of struct in one line? (in C)

I have a 2d array of structs like this, 我有这样的2d结构数组,

MapStruct myMap[50][50];

So we can initialize like this, 所以我们可以像这样初始化

myMap[0][0].left = 0;
myMap[0][0].up = 1;
myMap[0][0].right = 5;

I know that I can also use the below example, 我知道我也可以使用下面的例子,

MapStruct myMap[50][50] = { {0,1,5}, {2,3,7}, {9,11,8} ... };

But the problem is that there are significant empty spots in this 50x50 structure. 但问题是这个50x50结构中存在明显的空白点。 So for example maybe from [30][40] up to [40][50] is empty and some other points here and there are empty so with the above bracket notation i have to leave empty brackets like this {},{},{} for those empty spots. 所以例如可能从[30] [40]到[40] [50]是空的,其他一些点在这里有空,所以使用上面的括号表示法我必须留下像{},{}这样的空括号, {}对于那些空白点。

Now my question is is there a way to initialize the like below? 现在我的问题是有没有办法在下面初始化类似的?

myMap[0][0] = {0, 1, 5}; // gives a syntax error

Saves two lines per point I'd be pretty happy with that. 每点保存两行我会很满意。

Ps: I'm using the indices myMap[x][y] as keys like a dictionary object so I can't just get rid of those empty ones in the middle because that changes the indices. Ps:我使用索引myMap [x] [y]作为字典对象的键,所以我不能在中间摆脱那些空的因为这会改变索引。

C99 allows C99允许

myMap[0][0] = (MapStruct){0, 1, 5};

If you are restricted to C90, you can use an helper function. 如果您受限于C90,则可以使用辅助功能。

mypMap[4][2] = makeStruct(3, 6, 9);

But note that 但请注意

MapStruct myMap[50][50];

in a function won't initialize the array with 0 values if there are no initializer, so you'll have to use 如果没有初始化程序,函数中的函数将不会使用0值初始化数组,因此您必须使用

MapStruct myMap[50][50] = {0};

And also note that one may wonder if it is wize to allocate such big arrays on the stack. 并且还要注意,人们可能想知道在堆栈上分配如此大的数组是否是wize。

If you try with : 如果您尝试:

myMap[0][0] = (MapStruct) {.left = 0, .up = 1, .right = 5};

Or 要么

myMap[0][0] = (MapStruct) {0, 1, 5};

如果您正在使用C99,请查找复合文字。

C99 allows initialization like this: C99允许像这样的初始化:

MapStruct myMap[50][50] = {
    [ 0][ 5] = { /* ... */ },
    [10][20] = { /* ... */ },
    /* ... */
};

Or, you can set up the values by assignment, like this: 或者,您可以按分配设置值,如下所示:

MapStruct myMap[50][50];
/* ... */
myMap[ 0][ 5] = (MapStruct){ /* ... */ };
myMap[10][20] = (MapStruct){ /* ... */ };
/* ... */

Be aware that the syntax in the second method is not casting. 请注意,第二种方法中的语法不是强制转换。 It is notation introduced by C99 that, although it looks the same as a cast, is used to write literals of aggregate types. 它是由C99引入的符号,虽然它看起来像一个强制类型,但用于编写聚合类型的文字。

This will give you data on the heap rather than the stack but what you want to do could be achieved with calloc from <stdlib.h> . 这将为您提供堆而非堆栈的数据,但您可以使用<stdlib.h> calloc实现您想要做的事情。 calloc will allocate the memory space and it set initialize it to zero. calloc将分配内存空间,并将其初始化为零。

MyStruct * myMap = calloc( 50, 50 * sizeof(MyStruct));

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

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