数组的声明没有最高层面 [英] Declaration of an array without highest dimension

查看:140
本文介绍了数组的声明没有最高层面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这将是整型数组的维ARR如果声明如下:

what will be the dimension of integer array arr if declared like this :

int arr[][2]={1,2,3};

有什么用不申报最高层面?

what is the use of not declaring the highest dimension ?

推荐答案

有点出乎我的意料,你的宣言:

Somewhat to my surprise, your declaration:

int arr[][2]={1,2,3};

看起来是合法的。你可以合法地省略括号内的初始化。例如,如果你想定义的边界改编明确并初始化所有的元素,你可以写之一:

appears to be legal. You can legally omit inner braces in initializers. For example, if you wanted to define the bounds of arr explicitly and initialize all its elements, you could write either:

int arr[2][2] = { { 1, 2}, { 3, 4 } };

或等价地:

int arr[2][2] = { 1, 2, 3, 4 };

您也可以省略尾随的元素,他们将被隐式设置为零。为一个一维数组,这是简单的;这样的:

You can also omit trailing elements, and they'll be implicitly set to zero. For a one-dimensional array, this is straightforward; this:

int arr[4] = { 1, 2, 3 };

相当于:

int arr[4] = { 1, 2, 3, 0 };

和如果省略一个尺寸,它可以从初始推断:

And if you omit a dimension, it can be inferred from the initializer:

int arr[] = { 1, 2, 3, 4 }; // 4 elements

既然你定义改编 INT 的两个元素的数组,这个数组:

Since you're defining arr as an array of 2-element arrays of int, this:

int arr[][2]={1,2,3};

等同于这样的:

int arr[][2] = { { 1, 2 }, { 3 } };

您有在初始化两个元素(其中每一个初始化2元件阵列),所以这是等效于:

You have two elements in the initializer (each of which initializes a 2-element array), so that's equivalent to:

int arr[2][2] = { { 1, 2 }, { 3 } };

最后,你已经省略了最后的初始化子元素,所以它的隐含零:

Finally, you've omitted the last initializer sub-element, so it's implicitly zero:

int arr[2][2] = { { 1, 2 }, { 3, 0 } };

在一般情况下,省略尺寸和尾随初始化,因为它可以让编译器弄清楚一些事情是非常有用的。如果我写:

In general, omitting dimensions and trailing initializers is useful because it lets the compiler figure out certain things. If I write:

char message[] = "hello, world";

我没有在字符串中的计数字符(加1为终止'\\ 0')。计算机是在计数的东西确实不错;制作人做的工作将是愚蠢的。

I don't have to count the characters in the string (and add 1 for the terminating '\0'). Computers are really good at counting things; making a human do that job would be silly.

同样,忽略了一些初始化,您可以只提供您所需要的信息。随着C99的另外指定初始化的,你甚至可以初始化结构的指定成员,并让编译器打理一切的:

Similarly, omitting some initializers lets you provide only the information you need. With C99's addition of designated initializers, you can even initialize a specified member of a structure and let the compiler take care of everything else:

struct foo obj = { .something = 42 };

至于通过省略内花括号压扁初始化,我个人没有看到那么多的使用,除了使用 {0} 初始化初始化的特殊情况与整个数组或结构为零。特别是,对于多维数组我发现它的的更清楚,以显示该阵列的整个结构

As for flattening initializers by omitting inner curly braces, I personally don't see much use for that except for the special case of using a { 0 } initializer to initialize and entire array or structure to zero. In particular, for multidimensional arrays I find it much clearer to show the entire structure of the array.

这篇关于数组的声明没有最高层面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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