为什么在C中初始化n维数组时必须明确指定n-1维 [英] Why must n-1 dimensions be specified explicitly when initiailizing an n-dimensional array in c

查看:127
本文介绍了为什么在C中初始化n维数组时必须明确指定n-1维的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以如下明确地初始化一维数组:

I know I can explicitly initialize a 1-d array as follows:

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

此数组将恰好具有6个元素-sizeof(a1d) / sizeof(a1d[0])告诉我.

This array will have exactly 6 elements - sizeof(a1d) / sizeof(a1d[0]) tells me so.

我正在尝试使用二维(或更多)维数组:

I'm trying to do this with a 2- (or more) dimensional array:

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

但是error: array type has incomplete element type出现gcc错误. 从初始化看来,这显然是2x3数组,但似乎不允许这样做-为什么这样做?

But gcc errors with error: array type has incomplete element type. It would seem that it is explicit from the initialization that this is a 2x3 array, but it would seem this isn't allowed - why is this?

相反,我必须指定除一个尺寸外的所有尺寸:

Instead I have to specify all but one dimensions:

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

我了解,如果我要将n维数组传递给函数,则绝对有必要在函数中指定n-1维,如此问题

I understand that if I am going to pass an n-dimensional array to a function, then it is absolutely necessary for n-1 dimensions to be specified in the function, as explained by this question Why do we need to specify the column size when passing a 2D array as a parameter?, but it is less obvious to me for the explicitly-initialized case. Is this just a limitation of the standard, or is there a compelling technical reason for this I am missing?

推荐答案

一个原因是允许使用这样的初始化程序来初始化数组:

One reason is that it is permissible to initialize an array with an initializer like this:

= { { 1 }, { 2, 3 }, { 4, 5, 6 } };

没有必要提供每个初始化程序.实际上,使用指定的初始化程序,它可能会变成:

It is not obligatory to provide every initializer. Indeed, with designated initializers, that could become:

= { [23] = { 1 }, [9] = { 2, 3 }, [3] = { [13] = 4, [99] = 5, [0] = 6 } };

因此,作为初始化程序的数组必须至少为:

So the array that that is an initializer for must be at least:

int a[24][100];

部分地,它可以追溯到C的古老历史,当时编译器必须适合64 KiB内存等.编译器推论数组大小所需的额外工作可能对于C的容量来说实在太大了.机器(特别是与让用户明确指定他们想要的数组的大小(保存的类型最少)的成本相比).

Partly, it dates back to the ancient history of C when the compiler had to fit into 64 KiB memory, etc. The extra work needed to deduce the size of the array by the compiler was probably too great for the capacity of the machines (especially compared with the cost of having the user specify explicitly how big an array they wanted — the saved typing is minimal).

NB:允许"并不意味着推荐".

这篇关于为什么在C中初始化n维数组时必须明确指定n-1维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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