初始化整个二维数组与一个值 [英] Initializing entire 2D array with one value

查看:286
本文介绍了初始化整个二维数组与一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过以​​下声明

int array[ROW][COLUMN]={0};

我得到了所有零但具有下列之一阵列

I get the array with all zeroes but with the following one

int array[ROW][COLUMN]={1};

我不明白所有的一个值的数组。缺省值仍然是0。

I don’t get the array with all one value. The default value is still 0.

为什么这种行为,我怎么能初始化所有1?

Why this behavior and how can I initialize with all 1?

编辑:我刚才了解,使用 memset的以价值为1,将每个字节设置为1,因此每一个阵单元的实际值不会是1,但 16843009 。我该如何将它设置为1?

I have just understood that using memset with 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?

推荐答案

您得到这个行为,因为 int数组[ROW] [列] = {1} 的意思是将所有项目之一。让我试着解释这是如何工作一步一步来。

You get this behavior, because int array [ROW][COLUMN] = {1}; does not mean "set all items to one". Let me try to explain how this works step by step.

初​​始化阵列的明确,过于明显的方法是这样的:

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}
};

不过,C可以让你忽略了一些项目的一个数组(或结构/联合)。例如,你可以写:

However, C allows you to leave out some of the items in an array (or struct/union). You could for example write:

int array [ROW][COLUMN] =
{
  {1, 2}
};

这意味着,初始化第一元件1和2,以及仿佛他们有静态存储持续时间的要素的其他部分。有在C说静态存储持续时间的所有对象,未明确由程序员初始化,必须设置为零的规则。

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和下为0,0,因为我们没有给他们的任何显式值。

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.

接下来,在C允许松懈括号风格的规则。第一实例可以以及被写成

Next, there is a rule in C allowing lax brace style. The first example could as well be written as

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};

这意味着:在第一行的第一列初始化为0,因为如果他们有静态存储周期,即其设置为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."

因此​​,如果您尝试

int array [ROW][COLUMN] = {1};

它的意思是第一行中的第一列初始化为1,并设置所有其他项目零

it means "initialize the very first column in the first row to 1 and set all other items to zero".

这篇关于初始化整个二维数组与一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆