1

Regarding the code below, is there a way to initialize arr0[] and arr1[] to match one of the other two arrays chosen by the input parameter? Or is it possible to make arr0[] and arr1[] a constant array? Thanks.

#define LENGTH 4

void foo(char id) {

    const char arr_a0[] = {2,1,2,1};
    const char arr_a1[] = {4,5,6,7};

    const char arr_b0[] = {3,3,3,4};
    const char arr_b1[] = {1,5,8,9};

    char arr0[LENGTH];
    char arr1[LENGTH];
    int i;

    switch(id) {
    case 'a':
        for (i = 0; i < LENGTH; ++i) {
            arr0[i] = arr_a0[i];
            arr1[i] = arr_a1[i];
        }
        break;  

    case 'b':
    default:
        for (i = 0; i < LENGTH; ++i) {
            arr0[i] = arr_b0[i];
            arr1[i] = arr_b1[i];
        }
        break;
    }

    /* Do something with arr0[] and arr1[] */
}
3
  • 1
    Sounds like a XY problem. meta.stackexchange.com/questions/66377/what-is-the-xy-problem Commented Mar 27, 2018 at 5:14
  • 4
    Consider using pointers to arrays (initialised to point to one of the two arrays) later in the code, whereever the two arrays are used. Commented Mar 27, 2018 at 5:16
  • @Yunnosch Thanks., that's all I need. Gotta check my basics :) Commented Mar 27, 2018 at 13:05

1 Answer 1

1

It seems that you do not actually need to initialise two arrays, depending on some condition, from two constant arrays. (This is sometimes called an XY-problem.)

Your question whether the initiliased arrays can be made constant seems to indicate that you might work with two pointers.
Initialise those two pointers to each point to one of a pair of constant arrays.

Without the code using the two "conditionally initialised arrays" or, with the proposed alternative concept, uses the two pointers to constant arrays, this answer cannot give the full code solution for doing it.
I trust that your comment indicates that the basic concept has solved your problem.

Sign up to request clarification or add additional context in comments.

1 Comment

There are of course some traps, as always with using pointers, so feel free to update your question with something like "Edit: I got close to my goal with using pointers to constant arrays, but now ...". Ping me in a comment on your question and I will try to help.

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.