0

I have searched in a few places already for a solution to this problem and have come up short. Essentially what I am looking to do is to assign a const 1D array from one of the rows of a const 2d array and specifically to do it in a header file.

Say I have

const int Arr1[2][3] = {{1,2,3},{4,5,6}};

and I want to initialize an array (within a header file) from this array. I know normally I could do:

const int *Arr2 = Arr1[1];

or

const int *Arr2 = Arr1[0];

but doing so in a header file gives multiple definition errors. So my question is if there is a nice way to do this.

2 Answers 2

2

The multiple definition errors don't have anything to do with your assignment.

Just say in your header

 extern const int *Arr2;

and initialize it in a separate translation unit:

 const int Arr1[2][3] = {{1,2,3},{4,5,6}};
 const int *Arr2 = Arr1[1];

Maybe selectively from preprocessor directives:

 const int Arr1[2][3] = {{1,2,3},{4,5,6}};
 #ifdef ZERO_PATH
 const int *Arr2 = Arr1[0];
                     // ^ ZERO_PATH
 #else
 const int *Arr2 = Arr1[1];
 #endif
Sign up to request clarification or add additional context in comments.

Comments

0

Your code:

const int *Arr2 = Arr1[1];

initializes a pointer, not an array. Arrays and pointers are different. It's not clear from your post whether you're content with using a pointer, but if so then you either need to setup as in πάντα ῥεῖ's answer; or give Arr2 internal linkage:

const int *const Arr2 = Arr1[1];    // if you do not plan to change Arr2
static const int *Arr2 = Arr1[1];   // if you do

To actually use an array you can write:

const int Arr2[3] = { Arr1[1][0], Arr1[1][1], Arr1[1][2] };

There's no way to use a whole C-style array as initializer for another array of the same type. But if you use C++-style arrays you can do that:

const array<array<int, 3>, 2> Arr1 = {{ {1,2,3},{4,5,6} }};

const array<int, 3> Arr2 = Arr1[0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.