为什么初始化多维数组时不能完全省略维度

为什么初始化多维数组时不能完全省略维度

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

问题描述

在 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 抱怨这个数组可能不包含 'that' 类型的元素,编译后 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(8bit),并且大小未知.
  • char a[6]; 的元素大小为 1,大小为 6.
  • char a[][6]; 有元素(例如,a[0],它是一个数组)大小 6,并且大小未知.
  • char a[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.

不允许:

  • char a[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).

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

08-19 12:57