如何获取 3D 矩阵中数组的大小

  • 本文关键字:数组 3D 何获取 获取 c
  • 更新时间 :
  • 英文 :


考虑以下 3D 矩阵

char ShapesArray[2] = { 
  (char[4][4]){
    { 0, 1, 0, 0 }, //I
    { 0, 1, 0, 0 },
    { 0, 1, 0, 0 },
    { 0, 1, 0, 0 }
  }, 
  (char[3][3]){
    { 0, 1, 0 },    //J
    { 0, 1, 0 },
    { 1, 1, 0 }
  }
};

通过使用

int i = sizeof(ShapesArray[0]));

结果我预计会有 16 个。
但在这种情况下的结果是:1

我在这里错过了什么?

char ShapesArray[2]是一个由两个char组成的数组,因此第一个元素的大小为 1。打开编译器警告:

<source>: In function 'main':
<source>:4:2: error: initialization of 'char' from 'char (*)[4]' makes integer from pointer without a cast [-Werror=int-conversion]
    4 |  (char[4][4]) {
      |  ^
<source>:4:2: note: (near initialization for 'ShapesArray[0]')
<source>:10:2: error: initialization of 'char' from 'char (*)[3]' makes integer from pointer without a cast [-Werror=int-conversion]
   10 |  (char[3][3]) {
      |  ^
<source>:10:2: note: (near initialization for 'ShapesArray[1]')
cc1: all warnings being treated as errors
Compiler returned: 1

编译器所说的是,您正在使用char (*)[4]初始化charchar (*)[3]这是错误的。它甚至不会用C++编译器进行编译。

最新更新