当定义和声明分开时,如何一次性初始化数组的所有元素? [英] how to initialize all elements of an array at one go when definition and declaration are separate?
本文介绍了当定义和声明分开时,如何一次性初始化数组的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我们写这样的东西
int arr [5] = 0;
或 int arr [5] = {0};
没问题
但是当我们做这样的事情
but when we do something like this
int arr[5];
arr[5] = {0};
发生错误.有什么解释吗?
an error occurs. Any explanation for this ?
推荐答案
这只是语言定义的一部分,可以初始化数组,但不能直接分配数组.您可以使用带有复合文字的 memcpy()
在C99中执行所需的操作:
It is simply a part of the language definition that arrays can be initialised, but not directly assigned. You can do what you want in C99 using memcpy()
with a compound literal:
int arr[5];
/* ... */
memcpy(&arr, &(int [5]){ 0 }, sizeof arr);
使用GCC的 typeof
扩展名,您可以添加更多安全性:
With GCC's typeof
extension, you can add a little more safety:
memcpy(&arr, &(typeof(arr)){ 0 }, sizeof arr);
在C89中,您必须给源数组起一个名字:
In C89 you must give the source array a name:
{ static const int zero[5] = { 0 }; memcpy(&arr, &zero, sizeof arr); }
这篇关于当定义和声明分开时,如何一次性初始化数组的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文