Assigning an entire array with a single statement

后端 未结 5 1897
闹比i
闹比i 2021-01-11 20:53

Let us say that I declare and initialize

int a[3] = {1, 2, 3};

How can I later asisgn the entire array in one fell swoop? i.e.



        
5条回答
  •  半阙折子戏
    2021-01-11 21:29

    If your c compiler supports compound literals, you can use memcpy:

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

    If you don't plan to stick any variables in there (you can; isn't C99 amazing?), (int[]) can be replaced by (const int[]) to put the literal into static memory.

提交回复
热议问题