Declaring and initializing arrays in C

前端 未结 8 2116
北海茫月
北海茫月 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 03:50

    This is an addendum to the accepted answer by AndreyT, with Nyan's comment on mismatched array sizes. I disagree with their automatic setting of the fifth element to zero. It should likely be 5 --the number after 1,2,3,4. So I would suggest a wrapper to memcpy() to produce a compile-time error when we try to copy arrays of different sizes:

    #define Memcpy(a,b) do {                    /* copy arrays */       \
        ASSERT(sizeof(a) == sizeof(b) &&        /* a static assert */   \
               sizeof(a) != sizeof((a) + 0));   /* no pointers */       \
        memcpy((a), (b), sizeof (b));           /* & unnecesary */      \
        } while (0)                             /* no return value */
    

    This macro will generate a compile-time error if your array is of length 1. Which is perhaps a feature.

    Because we are using a macro, the C99 compound literal seems to need an extra pair of parentheses:

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

    Here ASSERT() is a 'static assert'. If you don't already have your own, I use the following on a number of platforms:

    #define CONCAT_TOKENS(a, b) a ## b
    #define EXPAND_THEN_CONCAT(a,b) CONCAT_TOKENS(a, b)
    #define ASSERT(e) enum {EXPAND_THEN_CONCAT(ASSERT_line_,__LINE__) = 1/!!(e)}
    #define ASSERTM(e,m) /* version of ASSERT() with message */ \
        enum{EXPAND_THEN_CONCAT(m##_ASSERT_line_,__LINE__)=1/!!(e)}
    

提交回复
热议问题