OrElse
OrElse

Reputation: 9959

How can I get the size of the array in an 3D matrix?

Consider the following 3D matrix

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 }
  }
};

by using

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

I would expect 16 as result.
But the result in this case is: 1

What am I missing here?

Upvotes: 2

Views: 118

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29975

char ShapesArray[2] is an array of two chars. Hence the first element's size is 1. Turn on the compiler warnings:

<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

What the compiler is saying is that you're initializing chars with char (*)[4] and char (*)[3] which is wrong. It wouldn't even compile with a C++ compiler.

Upvotes: 3

Related Questions