为什么我不能初始化多维数组时完全忽略尺寸是多少? [英] Why can't I omit the dimensions altogether when initializing a multi-dimensional array?

查看:195
本文介绍了为什么我不能初始化多维数组时完全忽略尺寸是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Visual Studio 2010中,这个初始化按预期工作:

In Visual Studio 2010, this initialization works as expected:

char table[2][2] = {
                       {'a', 'b'},
                       {'c', 'd'}
                   };

但它似乎没有法律写的东西,如:

But it does not seem legal to write something like:

char table[][] = {
                     {'a', 'b'},
                     {'c', 'd'}
                 };

Visual Studio中抱怨说,这个阵列可能不包含的内容说的类型,并编译之后,VS报告两个错误:缺失索引和太多的初始化

Visual Studio complains that this array may not contain elements of 'that' type, and after compiling, VS reports two errors: a missing index and too many initializations.

:为什么我不能完全忽略尺寸初始化多维数组时?

QUESTION: Why can't I omit the dimensions altogether when initializing a multi-dimensional array?

推荐答案

只有最内部尺寸可以省略。数组中元素的大小推导为给数组变量的类型。因此,型元件必须具有已知尺寸

Only the innermost dimension can be omitted. The size of elements in an array are deduced for the type given to the array variable. The type of elements must therefore have a known size.


  • 的char a []; 有大小的元素(如 A [0] 1(8位),并具有一个未知大小。

  • 一个烧焦[6]; 有大小的元素 1,并有大小6

  • 的char a [] [6]; 有元素(如 A [0] ,这是一个数组大小) 6,并具有一个未知大小。

  • 一个烧焦[10] [6]; 有大小的元素 6,拥有大小60

  • char a[]; has elements (e.g. a[0]) of size 1 (8bit), and has an unknown size.
  • char a[6]; has elements of size 1, and has size 6.
  • char a[][6]; has elements (e.g. a[0], which is an array) of size 6, and has an unknown size.
  • char a[10][6]; has elements of size 6. and has size 60.

不允许


  • 一个烧焦[10] []; 将有10个元素未知大小的

  • 的char a [] []; 将有数量不明的未知大小的元素

  • char a[10][]; would have 10 elements of unknown size.
  • char a[][]; would have an unknown number of elements of unknown size.

元素的大小是强制性的,编译器需要它来访问元件(通过指针运算)。

The size of elements is mandatory, the compiler needs it to access elements (through pointer arithmetic).

这篇关于为什么我不能初始化多维数组时完全忽略尺寸是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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