可以在一行中(重新)设置数组的所有值(在初始化之后)吗?
在C中,我知道我可以创建一个像这样的数组
int myarray[5] = {a,b,c,d,e};
但是,想象一下数组已经被初始化了
int myarray[5];
,然后在之后的某个时刻,我想设置/更改所有值而不用去
myarray[0] = a;
myarray[1] = b;
myarray[2] = c;
myarray[3] = d;
myarray[4] = e;
,而是更像是
myarray = {a,b,c,d,e};
我问的原因这是因为如果我在堆上声明我的数组,我将像这样初始化数组:
int* myarray = malloc(5*sizeof(int));
然后我希望能够在一行中输入所有值(主要是为了让我的代码看起来更干净)
In C, I know I can make an array like this
int myarray[5] = {a,b,c,d,e};
However, imagine the array was already initialised like
int myarray[5];
and then at some point afterwards, I wanted to set/change all the values without going
myarray[0] = a;
myarray[1] = b;
myarray[2] = c;
myarray[3] = d;
myarray[4] = e;
but rather, something more like
myarray = {a,b,c,d,e};
The reason why I ask this is because if I declare my array on the heap, I will initialise the array like:
int* myarray = malloc(5*sizeof(int));
Then I would like to be able to enter in all the values in one line (mostly to make my code look cleaner)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个兼容所有标准(C89、C99、C++)的解决方案,
它的优点是您只需担心在一个地方输入数据。其他代码都不需要更改 - 没有神奇的数字。数组在堆上声明。数据表被声明为 const。
(单击此处尝试在键盘中运行它)
Here is a solution that is all standards compatible (C89, C99, C++)
It has the advantage that you only worry about entering the data in one place. None of the other code needs to change - there are no magic numbers. Array is declared on the heap. The data table is declared const.
(Click here to try running it in Codepad)
不,C 没有这样的功能。如果要将所有数组元素设置为相同的值,请使用
memset(3)
。No, C doesn't have such feature. If you are setting all array elements to the same value use
memset(3)
.