简体   繁体   中英

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

I have a 2d array of structs like this,

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. 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.

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.

C99 allows

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

If you are restricted to C90, you can use an helper function.

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

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

And also note that one may wonder if it is wize to allocate such big arrays on the stack.

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:

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.

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> . calloc will allocate the memory space and it set initialize it to zero.

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

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