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

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

问题描述

带有以下声明

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 array [ROW][COLUMN] = {1};not 的意思是将所有项目设置为一个".让我试着逐步解释这是如何工作的.

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,所有其他项目就好像它们具有静态存储持续时间一样,即将它们设置为零."

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天全站免登陆