简单的C数组声明/赋值问题
在更高级别的语言中,我可以用 C 语言实现与此示例类似的功能,这样就很好了。然而,当我编译这个 C 示例时,它抱怨得很厉害。如何将新数组分配给我声明的数组?
int values[3];
if(1)
values = {1,2,3};
printf("%i", values[0]);
谢谢。
In higher level languages I would be able something similar to this example in C and it would be fine. However, when I compile this C example it complains bitterly. How can I assign new arrays to the array I declared?
int values[3];
if(1)
values = {1,2,3};
printf("%i", values[0]);
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
当您声明数组时,您只能对数组进行多重赋值:
声明后,您必须单独分配每个值,即,
或者您可以使用循环,具体取决于您要使用的值。
You can only do multiple assignment of the array, when you declare the array:
After declaration, you'll have to assign each value individually, i.e.
Or you could use a loop, depending on what values you want to use.
在 C99 中,使用 复合文字,您可以执行
以下操作:
In C99, using compound literals, you could do:
or
您可以声明静态数组并包含要初始化的数据:
you can declare static array with data to initialize from:
还可以通过使用编译器的结构块副本来隐藏 memcpy。由于所有 .i 和 i: 它使代码变得丑陋,但也许它可以解决您的特定问题。
It is also possible to hide the memcpy by using the compiler's block copy of structs. It makes the code ugly because of all the .i and i: but maybe it solves your specific problem.
还有这个...:)
测试一下如果声明 S[8] 或 S[32] 会发生什么,看看为什么这如此有效。
我根据 OpenBSD 的 strlcpy 逻辑编写了自己的字符串函数,旨在确保在溢出时必须存在终止符字节,而标准 strncpy 不会这样做,因此您必须仔细观察如何使用它。
上面的方法是有效的,因为声明处的
=""
确保整个过程都是 0 个字节,并且sizeof(S)-1
确保如果您过度传递给 strncpy 的带引号的字符串,您会得到截断并且不会违反最后 0 字节,因此现在可以安全地防止溢出,并且以后访问字符串时也可以安全地防止溢出。我的目标是 ANSI C,所以它在任何地方都应该是安全的。There is also this... :)
Test what happens if you declare S[8] or S[32], to see why this is so effective.
I wrote my own string functions based on the logic of OpenBSD's strlcpy, aimed at ensuring a terminator byte MUST exist in the event of overflow, and standard strncpy won't do this so you have to watch carefully how you use it.
The method above is effective because the
=""
at declaration ensures 0 bytes throughout, andsizeof(S)-1
ensures that if you overdo the quoted string passed to strncpy, you get truncation and no violation of the last 0 byte, so this is safe against overflow now, AND on accessing the string later. I aimed this at ANSI C so it ought to be safe anywhere.我会将其作为评论发布,但我没有足够的声誉。初始化数组的另一种(可能是肮脏的)方法是将其包装在结构中。
I would post this as a comment, but I don't have enough reputation. Another (perhaps dirty) way of initializing an array is to wrap it in a struct.
这在带有 -O3 的 gcc 下工作和优化得更好(编译器完全删除代码),而 memcpy 强制在所有情况下复制内存。
This works and optimizes better under gcc with -O3 (the compiler completely removes the code), whereas the memcpy forces the memory to be copied in all cases.