Declaring and initializing arrays in C

前端 未结 8 2130
北海茫月
北海茫月 2020-12-01 03:15

Is there a way to declare first and then initialize an array in C?

So far I have been initializing an array like this:

int myArray[SIZE] = {1,2,3,4..         


        
8条回答
  •  无人及你
    2020-12-01 04:11

    The OP left out some crucial information from the question and only put it in a comment to an answer.

    I need to initialize after declaring, because will be different depending on a condition, I mean something like this int myArray[SIZE]; if(condition1) { myArray{x1, x2, x3, ...} } else if(condition2) { myArray{y1, y2, y3, ...} } . . and so on...

    With this in mind, all of the possible arrays will need to be stored into data somewhere anyhow, so no memcpy is needed (or desired), only a pointer and a 2d array are required.

    //static global since some compilers build arrays from instruction data
    //... notably not const though so they can later be modified if needed
    #define SIZE 8
    static int myArrays[2][SIZE] = {{0,1,2,3,4,5,6,7},{7,6,5,4,3,2,1,0}};
    
    static inline int *init_myArray(_Bool conditional){
      return myArrays[conditional];
    }
    
    // now you can use:
    //int *myArray = init_myArray(1 == htons(1)); //any boolean expression
    

    The not-inlined version gives this resulting assembly on x86_64:

    init_myArray(bool):
            movzx   eax, dil
            sal     rax, 5
            add     rax, OFFSET FLAT:myArrays
            ret
    myArrays:
            .long   0
            .long   1
            .long   2
            .long   3
            .long   4
            .long   5
            .long   6
            .long   7
            .long   7
            .long   6
            .long   5
            .long   4
            .long   3
            .long   2
            .long   1
            .long   0
    

    For additional conditionals/arrays, just change the 2 in myArrays to the desired number and use similar logic to get a pointer to the right array.

提交回复
热议问题