Declaring and initializing arrays in C

前端 未结 8 2084
北海茫月
北海茫月 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:15

    In C99 you can do it using a compound literal in combination with memcpy

    memcpy(myarray, (int[]) { 1, 2, 3, 4 }, sizeof myarray);
    

    (assuming that the size of the source and the size of the target is the same).

    In C89/90 you can emulate that by declaring an additional "source" array

    const int SOURCE[SIZE] = { 1, 2, 3, 4 }; /* maybe `static`? */
    int myArray[SIZE];
    ...
    memcpy(myarray, SOURCE, sizeof myarray);
    
    0 讨论(0)
  • 2020-12-01 04:15

    Why can't you initialize when you declare?

    Which C compiler are you using? Does it support C99?

    If it does support C99, you can declare the variable where you need it and initialize it when you declare it.

    The only excuse I can think of for not doing that would be because you need to declare it but do an early exit before using it, so the initializer would be wasted. However, I suspect that any such code is not as cleanly organized as it should be and could be written so it was not a problem.

    0 讨论(0)
提交回复
热议问题