在一行中初始化一个结构体数组? (在C中)
我有一个像这样的二维结构数组,
MapStruct myMap[50][50];
所以我们可以像这样初始化,
myMap[0][0].left = 0;
myMap[0][0].up = 1;
myMap[0][0].right = 5;
我知道我也可以使用下面的示例,
MapStruct myMap[50][50] = { {0,1,5}, {2,3,7}, {9,11,8} ... };
但问题是这个 50x50 结构中有明显的空点。例如,从 [30][40] 到 [40][50] 可能是空的 这里和那里的其他一些点都是空的,所以使用上面的括号表示法,我必须为这些空点留下像这样的空括号 {},{},{} 。
现在我的问题是有没有办法像下面这样初始化?
myMap[0][0] = {0, 1, 5}; // gives a syntax error
每点节省两行,我对此感到非常满意。
Ps:我使用索引 myMap[x][y] 作为像字典对象一样的键,所以我不能仅仅删除中间的那些空索引,因为这会改变索引。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C99 允许
如果您仅限于 C90,则可以使用辅助函数。
但请注意,
如果没有初始化程序,函数中不会用 0 值初始化数组,因此您必须使用
并且还要注意,人们可能想知道在堆栈上分配这么大的数组是否明智。
C99 allows
If you are restricted to C90, you can use an helper function.
But note that
in a function won't initialize the array with 0 values if there are no initializer, so you'll have to use
And also note that one may wonder if it is wize to allocate such big arrays on the stack.
如果你尝试使用:
或者
If you try with :
Or
C99 允许这样初始化:
或者,您可以通过赋值来设置值,如下所示:
请注意,第二个方法中的语法不是转换。它是 C99 引入的表示法,虽然看起来与强制转换相同,但用于编写聚合类型的文字。
C99 allows initialization like this:
Or, you can set up the values by assignment, like this:
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,请查找复合文字。
If you're using C99, look up compound literal.
这将为您提供堆上而不是堆栈上的数据,但您想要做的事情可以通过
中的 calloc 来实现。 calloc 将分配内存空间并将其初始化为零。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.