How to initialize all members of an array to the same value?

后端 未结 23 1903
清歌不尽
清歌不尽 2020-11-21 04:34

I have a large array in C (not C++ if that makes a difference). I want to initialize all members of the same value.

I could swear I

23条回答
  •  不思量自难忘°
    2020-11-21 05:27

    I saw some code that used this syntax:

    char* array[] = 
    {
        [0] = "Hello",
        [1] = "World"
    };   
    

    Where it becomes particularly useful is if you're making an array that uses enums as the index:

    enum
    {
        ERR_OK,
        ERR_FAIL,
        ERR_MEMORY
    };
    
    #define _ITEM(x) [x] = #x
    
    char* array[] = 
    {
        _ITEM(ERR_OK),
        _ITEM(ERR_FAIL),
        _ITEM(ERR_MEMORY)
    };   
    

    This keeps things in order, even if you happen to write some of the enum-values out of order.

    More about this technique can be found here and here.

提交回复
热议问题