1

I want the following

int ring1[5] = {1,2,3,4,5};
int ring2[5] = {6,7,8,9,10};
int ring3[5] = {11,12,13,14,15};
int rings[3][5] = {ring1, ring2, ring3};

But I get an error on the last line:

Array Must be initialized with a brace-enclosed initializer.

BvdVen
  • 2,921
  • 23
  • 33
  • 1
    Time to open up your text-book on the chapters on *pointers*. – Some programmer dude Dec 10 '20 at 11:25
  • 1
    Arrays cannot be copied by assignment. They can be copied with `memcpy` or element by element in a loop. You could make `rings` into an array of pointers, e.g. `int *rings[3] = {ring1, ring2, ring3};` but note that any changes to `ring1[i]` will also change `rings[0][i]` and vice versa. Likewise for `ring2` and `ring3`. – user3386109 Dec 10 '20 at 11:27
  • dupe of [C array declaration and assignment?](https://stackoverflow.com/questions/744536/c-array-declaration-and-assignment), etc. – underscore_d Dec 10 '20 at 11:42
  • The error is kind of misleading , are you compiling using `C++` compiler? – IrAM Dec 10 '20 at 11:42
  • @IrAM Arduino is quasi-C++, so kinda yeah. – underscore_d Dec 10 '20 at 11:56

1 Answers1

2

In C name of the array indicates the base address of the array, so all of your ring1, ring2 and ring3 gives the address of their starting element (i.e 0th).

Similarly rings is also an array (Its a 2 Dimensional array).

We cannot store address in arrays, for that will have to use pointers.

So we have to use below way.

#include <stdio.h>

int main()
{
    int ring1[5] = {1,2,3,4,5};
    int ring2[5] = {6,7,8,9,10};
    int ring3[5] = {11,12,13,14,15};
    //int rings[3][5] = {{ring1}, {ring2}, {ring3}};
    int *rings[3] = {ring1, ring2, ring3};
    
    printf("ring1 = %p and rings[0] =%p\n", ring1, rings[0]);
    printf("ring2 = %p and rings[1] =%p\n", ring1, rings[1]);
    printf("ring3 = %p and rings[2] =%p\n", ring1, rings[2]);

    return 0;
}
IrAM
  • 1,720
  • 5
  • 18
  • Yeah, but this loses the size info for the 'nested' arrays, and other issues from using pointers. A less direct but more correct fix would be to iterate and assign the sub-arrays IMO – underscore_d Dec 10 '20 at 11:57