C语言 用一个值初始化整个二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15520880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initializing entire 2D array with one value
提问by Kraken
With the following declaration
使用以下声明
int array[ROW][COLUMN]={0};
I get the array with all zeroes but with the following one
我得到的数组全为零,但有以下一个
int array[ROW][COLUMN]={1};
I don't get the array with all one value. The default value is still 0.
我没有得到所有一个值的数组。默认值仍然是 0。
Why this behavior and how can I initialize with all 1?
为什么会出现这种行为以及如何用全 1 进行初始化?
EDIT: I have just understood that using memsetwith value as 1, will set each byte as 1 and hence the actual value of each array cell wont be 1 but 16843009. How do I set it to 1?
编辑:我刚刚了解到,使用memset值为 1 时,会将每个字节设置为 1,因此每个数组单元格的实际值不会是 1,而是16843009。我如何将其设置为 1?
回答by Lundin
You get this behavior, because int array [ROW][COLUMN] = {1};does notmean "set all items to one". Let me try to explain how this works step by step.
你遇到这个问题,因为int array [ROW][COLUMN] = {1};确实不是意味着“设置的所有项目之一”。让我尝试逐步解释这是如何工作的。
The explicit, overly clear way of initializing your array would be like this:
初始化数组的明确、过于清晰的方法如下:
#define ROW 2
#define COLUMN 2
int array [ROW][COLUMN] =
{
{0, 0},
{0, 0}
};
However, C allows you to leave out some of the items in an array (or struct/union). You could for example write:
但是,C 允许您省略数组(或结构/联合)中的某些项目。例如,您可以编写:
int array [ROW][COLUMN] =
{
{1, 2}
};
This means, initialize the first elements to 1 and 2, and the rest of the elements "as if they had static storage duration". There is a rule in C saying that all objects of static storage duration, that are not explicitly initialized by the programmer, must be set to zero.
这意味着,将第一个元素初始化为 1 和 2,其余元素“就好像它们具有静态存储持续时间”。C 中有一条规则是所有静态存储持续时间的对象,没有被程序员显式初始化,必须设置为零。
So in the above example, the first row gets set to 1,2 and the next to 0,0 since we didn't give them any explicit values.
所以在上面的例子中,第一行被设置为 1,2,下一行被设置为 0,0,因为我们没有给它们任何明确的值。
Next, there is a rule in C allowing lax brace style. The first example could as well be written as
接下来,C 中有一条规则允许松散的大括号样式。第一个例子也可以写成
int array [ROW][COLUMN] = {0, 0, 0, 0};
although of course this is poor style, it is harder to read and understand. But this rule is convenient, because it allows us to write
虽然这当然是糟糕的风格,但更难阅读和理解。但是这个规则很方便,因为它允许我们写
int array [ROW][COLUMN] = {0};
which means: "initialize the very first column in the first row to 0, and all other items as if they had static storage duration, ie set them to zero."
这意味着:“将第一行中的第一列初始化为 0,所有其他项目就好像它们具有静态存储持续时间一样,即将它们设置为零。”
therefore, if you attempt
因此,如果您尝试
int array [ROW][COLUMN] = {1};
it means "initialize the very first column in the first row to 1 and set all other items to zero".
它的意思是“将第一行的第一列初始化为 1,并将所有其他项目设置为零”。
回答by user2021512
If you want to initialize the array to -1then you can use the following,
如果要将数组初始化为,-1则可以使用以下内容,
memset(array, -1, sizeof(array[0][0]) * row * count)
But this will work 0and -1only
但这会起作用,0并且-1只有
回答by teppic
int array[ROW][COLUMN]={1};
This initialises only the firstelement to 1. Everything else gets a 0.
这仅将第一个元素初始化为 1。其他所有元素都为 0。
In the first instance, you're doing the same - initialising the first element to 0, and the rest defaults to 0.
在第一种情况下,您正在执行相同的操作 - 将第一个元素初始化为 0,其余元素默认为 0。
The reason is straightforward: for an array, the compiler will initialise every value you don't specify with 0.
原因很简单:对于数组,编译器会将您未指定为 0 的每个值初始化。
With a chararray you could use memsetto set every byte, but this will not generally work with an intarray (though it's fine for 0).
使用char数组,您可以memset用来设置每个字节,但这通常不适用于int数组(尽管它可以用于 0)。
A general forloop will do this quickly:
一般for循环将快速完成此操作:
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COLUMN; j++)
array[i][j] = 1;
Or possibly quicker (depending on the compiler)
或者可能更快(取决于编译器)
for (int i = 0; i < ROW*COLUMN; i++)
*((int*)a + i) = 1;
回答by Jonathan Leffler
Note that GCC has an extension to the designated initializernotation which is very useful for the context. It is also allowed by clangwithout comment (in part because it tries to be compatible with GCC).
请注意,GCC 对指定的初始化符号进行了扩展,这对于上下文非常有用。也允许clang不加注释(部分原因是它试图与 GCC 兼容)。
The extension notation allows you to use ...to designate a range of elements to be initialized with the following value. For example:
扩展符号允许您使用...以下值指定要初始化的元素范围。例如:
#include <stdio.h>
enum { ROW = 5, COLUMN = 10 };
int array[ROW][COLUMN] = { [0 ... ROW-1] = { [0 ... COLUMN-1] = 1 } };
int main(void)
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COLUMN; j++)
printf("%2d", array[i][j]);
putchar('\n');
}
return 0;
}
The output is, unsurprisingly:
不出所料,输出是:
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
Note that Fortran 66 (Fortran IV) had repeat counts for initializers for arrays; it's always struck me as odd that C didn't get them when designated initializers were added to the language. And Pascal uses the 0..9notation to designate the range from 0 to 9 inclusive, but C doesn't use ..as a token, so it is not surprising that was not used.
请注意,Fortran 66 (Fortran IV) 对数组的初始值设定项有重复计数;当指定的初始值设定项添加到语言中时,C 没有得到它们总是让我感到奇怪。并且 Pascal 使用0..9符号来指定从 0 到 9 的范围,但 C 不用..作标记,因此没有使用也就不足为奇了。
Note that the spaces around the ...notation are essentially mandatory; if they're attached to numbers, then the number is interpreted as a floating point number. For example, 0...9would be tokenized as 0., ., .9, and floating point numbers aren't allowed as array subscripts.
With the named constants, ...ROW-1would not cause trouble, but it is better to get into the safe habits.
请注意,...符号周围的空格基本上是强制性的;如果它们附加到数字,则该数字被解释为浮点数。例如,0...9将被标记为0.、.、.9和浮点数不允许作为数组下标。使用命名常量,...ROW-1不会造成麻烦,但最好养成安全的习惯。
Addenda:
附加物:
I note in passing that GCC 7.3.0 rejects:
我顺便指出 GCC 7.3.0 拒绝:
int array[ROW][COLUMN] = { [0 ... ROW-1] = { [0 ... COLUMN-1] = { 1 } } };
where there's an extra set of braces around the scalar initializer 1(error: braces around scalar initializer [-Werror]). I'm not sure that's correct given that you can normally specify braces around a scalar in int a = { 1 };, which is explicitly allowed by the standard. I'm not certain it's incorrect, either.
在标量初始值设定项1( error: braces around scalar initializer [-Werror])周围有一组额外的大括号。我不确定这是否正确,因为您通常可以在标量 in 周围指定大括号int a = { 1 };,这是标准明确允许的。我也不确定这是不正确的。
I also wonder if a better notation would be [0]...[9]— that is unambiguous, cannot be confused with any other valid syntax, and avoids confusion with floating point numbers.
我还想知道是否有更好的表示法[0]...[9]- 即明确的,不能与任何其他有效语法混淆,并避免与浮点数混淆。
int array[ROW][COLUMN] = { [0]...[4] = { [0]...[9] = 1 } };
Maybe the standards committee would consider that?
也许标准委员会会考虑?
回答by Gaurav Suthar
To initialize 2d array with zero use the below method:
int arr[n][m] = {};
要使用零初始化二维数组,请使用以下方法:
int arr[n][m] = {};
NOTE: The above method will only work to initialize with 0;
注意:上述方法只能用 0 初始化;
回答by Jogendra Kumar
Use vectorarray instead:
改用向量数组:
vector<vector<int>> array(ROW, vector<int>(COLUMN, 1));

