在C语言中,如何在创建多维数组后立即分配多个值?

时间:2022-06-06 21:42:36

I'm programming in C and wonder if it's possible to assign multiple values at once to a multi-dimensional array? I have tried some technique but all have failed! I’m NOT interested to loop through the array to assign values (I want the fasted way to assign new values to all index in the array). The array I’m working with: ary[4][4].

我用C编程,想知道是否可以将多个值一次性分配给多维数组?我试过一些技巧,但都失败了!我对循环遍历数组来分配值不感兴趣(我希望用快速的方式为数组中的所有索引分配新值)。我正在处理的数组:ary[4][4]。

2 个解决方案

#1


2  

Since an array is not a modifiable lvalue, it cannot appear on the left side of an assignment. You can initialize it and you can assign individual members via indexing.

由于数组不是可修改的lvalue,所以它不能出现在赋值的左侧。您可以初始化它,并且您可以通过索引分配单个成员。

6.3.2.1

6.3.2.1

A modifiable lvalue is an lvalue that does not have array type, does not have ...

可修改的lvalue是没有数组类型、没有…

And a modifiable lvalue:

和一个可修改的左值:

The name ‘‘lvalue’’ comes originally from the assignment expression E1 = E2, in which the left operand E1 is required to be a (modifiable) lvalue.

“lvalue”的名称源自赋值表达式E1 = E2,其中左操作数E1必须为(可修改的)lvalue。

So no, you can't do what you want.

不,你不能做你想做的。

#2


3  

memcpy from another one will overwrite what is already in ary.

来自另一个的memcpy将覆盖已有的ary。

int ary[4][4];
int another[4][4] = {{1,2,3,4}, {5,6,7,8}, {1,2,3,4}, {5,6,7,8}};
memcpy(ary, another, 4 * 4 * sizeof(int));

#1


2  

Since an array is not a modifiable lvalue, it cannot appear on the left side of an assignment. You can initialize it and you can assign individual members via indexing.

由于数组不是可修改的lvalue,所以它不能出现在赋值的左侧。您可以初始化它,并且您可以通过索引分配单个成员。

6.3.2.1

6.3.2.1

A modifiable lvalue is an lvalue that does not have array type, does not have ...

可修改的lvalue是没有数组类型、没有…

And a modifiable lvalue:

和一个可修改的左值:

The name ‘‘lvalue’’ comes originally from the assignment expression E1 = E2, in which the left operand E1 is required to be a (modifiable) lvalue.

“lvalue”的名称源自赋值表达式E1 = E2,其中左操作数E1必须为(可修改的)lvalue。

So no, you can't do what you want.

不,你不能做你想做的。

#2


3  

memcpy from another one will overwrite what is already in ary.

来自另一个的memcpy将覆盖已有的ary。

int ary[4][4];
int another[4][4] = {{1,2,3,4}, {5,6,7,8}, {1,2,3,4}, {5,6,7,8}};
memcpy(ary, another, 4 * 4 * sizeof(int));