Olivier Pons Olivier Pons - 2 months ago 9
C Question

Assign pointer to const

Here's what I'm doing:

const uint16_t LAYERS_RIGHT[TOTAL_LAYERS][NBROW][NBCOL] = {
{{c00, c10, c20, c30, c40, c50, c60},
{c01, c11, c21, c31, c41, c51, c61},
{c02, c12, c22, c32, c42, c52, c62},
{c03, c13, c23, c33, c43, c53, c63},
{c04, c14, c24, c34, c44, c54, c64},
{c05, c15, c25, c35, c45, c55, c65}}
/* blah blah */
};
const uint16_t LAYERS_LEFT[TOTAL_LAYERS][NBROW][NBCOL] = {
/* blah blah */
/* blah blah */
};

uint16_t *(LAYERS[TOTAL_LAYERS][NBROW][NBCOL]);


My goal is try to make a pointer to that either right structure or left structure:

LAYERS = &LAYERS_RIGHT;


The compiler says:

error: incompatible types in assignment of
'const uint16_t (*)[7][6][7] {aka const unsigned int (*)[7][6][7]}' to
'uint16_t* [7][6][7] {aka unsigned int* [7][6][7]}'


How to make my code work?

Answer

You have LAYERS defined as a 3D array of pointers. You want a const pointer to a 3D array:

const uint16_t (*LAYERS)[TOTAL_LAYERS][NBROW][NBCOL];

To use this however, you need to use syntax like this:

(*LAYERS)[a][b][c];

If you want to index LAYERS as a 3D array, you can instead define it like this:

const uint16_t (*LAYERS)[NBROW][NBCOL];

And assign it like this:

LAYERS = LAYERS_RIGHT;

This takes advantage of the fact that in some contexts an array decays into a pointer to the first element. The above assignment is one of them.

LAYERS_RIGHT is an array of const uint16_t [NBROW][NBCOL], so the type of the address of one of these array elements is const uint16_t (*)[NBROW][NBCOL], which is the type of LAYERS.

Then LAYERS[0] references the first const uint16_t [NBROW][NBCOL], LAYERS[1], the second, and so forth.

So after the above assignments, this expression

LAYERS_RIGHT[a][b][c];

Yields the same value as this expression:

LAYERS[a][b][c];
Comments