0

I'm storing some arrays like this:

uint8_t a[2][4][4] = {
{
    { 1, 1, 1, 1 },
    { 0, 0, 0, 0 },
    { 0, 0, 0, 0 },
    { 0, 0, 0, 0 },
},
{
    { 1, 1, 1, 0 },
    { 1, 0, 0, 0 },
    { 0, 0, 0, 0 },
    { 0, 0, 0, 0 },
},
};

and, then I store an array of this arrays:

uint8_t ***data[5] = { 0, 0, (uint8_t ***)a, (uint8_t ***)b, (uint8_t ***)c};

so when I try to cout<<data[2][0][0][1]; it should print 1 but an read access violation exception occurs. why this doesn't work?

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
alireza_fn
  • 884
  • 1
  • 8
  • 21
  • 3
    Arrays are **not** pointers. – MikeCAT Mar 06 '16 at 23:45
  • 3
    To rephrase the above comment more specifically: `uint8_t ***` is not the same type as `uint8_t ()[2][4][4]` and cannot be used interchangably as you are doing. Here is a longer explanation of how multi dimensional arrays are layed out in memory and why you can't just interchange that with aribtrary multi star pointers: [How are multi-dimensional arrays formatted in memory?](https://stackoverflow.com/questions/2565039/how-are-multi-dimensional-arrays-formatted-in-memory) – kaylum Mar 06 '16 at 23:50
  • 2
    `uint8_t ***data[5] = { 0, 0, (uint8_t ***)a, (uint8_t ***)b, (uint8_t ***)c};` -- Remove the casts. What compiler error do you get? If you did get compile errors, please take the errors that the compiler is giving you seriously, and not try to cover them up by casting – PaulMcKenzie Mar 07 '16 at 00:05

1 Answers1

2

(uint8_t ***)a has the compiler interpret what is pointed by (pointer converted from) a as uint8_t**, but what there actually is data in the array, say, 0x01010101 if pointers are 4-byte long. There are little chance to the number to be a valid address, so dereferencing the "pointer" will lead to Segmentation Fault.

Use correct type.

uint8_t (*data[5])[4][4] = { 0, 0, a, b, c};

Also the statement to print should be

cout<<(int)data[2][0][0][1];

otherwise, the number may be interpreted as character and something not readable may be printed.

alireza_fn
  • 884
  • 1
  • 8
  • 21
MikeCAT
  • 73,922
  • 11
  • 45
  • 70