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.

5
  • 1
    Time to open up your text-book on the chapters on pointers. Commented Dec 10, 2020 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. Commented Dec 10, 2020 at 11:27
  • dupe of C array declaration and assignment?, etc. Commented Dec 10, 2020 at 11:42
  • The error is kind of misleading , are you compiling using C++ compiler? Commented Dec 10, 2020 at 11:42
  • @IrAM Arduino is quasi-C++, so kinda yeah. Commented Dec 10, 2020 at 11:56

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.