initializing an array of ints

前端 未结 7 829
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 05:00

Does anyone have a way to initialize an array of ints (any multi-byte type is fine really), to a non-zero and non -1 value simply? By which I mean, is there a w

相关标签:
7条回答
  • 2020-11-29 05:35
    for (count = 0; count < 30; count++) arr[count] = 1;
    

    One line. :)

    0 讨论(0)
  • 2020-11-29 05:37

    For initialization to a static value, I have generally considered typing it out to be preferred, as in:

    int arr[30] = {1, 1, 1, 1, ...}; 
    

    In this case, the compiler can (and usually does) spit out optimized initialization in preamble code.

    Sometimes the initialization is more dynamic, as in this example:

    int arr[30];
    int x = fetchSomeValue();
    for(int i=0; i<30; i++) arr[i] = x;
    

    In these cases you have to code it and the general rule is to maximize readability, not minimize typing. This code will be written once and read a multitude of times.

    0 讨论(0)
  • 2020-11-29 05:42

    In C you typically develop your own "support library" with macros like

    #define SET_ALL(a_, n_, v_)\
      do { size_t i, n = (n_); for (i = 0; i < n; ++i) (a_)[i] = (v_); } while(0)
    
    #define SET_ALL_A(a_, v_) SET_ALL(a_, sizeof(a_) / sizeof *(a_), v_)
    #define ZERO_ALL(a_, n_) SET_ALL(a_, n_, 0)
    #define ZERO_ALL_A(a_) SET_ALL_A(a_, 0)
    

    and then use them in your code as

    int arr[30];
    
    SET_ALL_A(arr, 1);
    
    0 讨论(0)
  • 2020-11-29 05:48

    The only sensible way to do this during initialization (rather than runtime) seems to be:

    #define ONE1     1
    #define FIVE1    ONE1, ONE1, ONE1, ONE1, ONE1
    #define TEN1     FIVE1, FIVE1
    #define TWENTY1  TEN1, TEN1
    #define FIFTY1   TWENTY1, TWENTY1, TEN1
    #define HUNDRED1 FIFTY1, FIFTY1
    
    int array [100][4] =
    {
      HUNDRED1,
      HUNDRED1,
      HUNDRED1,
      HUNDRED1
    };
    

    And next, #define ONE2 2 and so on. You get the idea.

    EDIT : The reason why I wrote so many macros was to demonstrate how flexible this solution is. For this particular case you don't need all of them. But with macros like these you can write any kind of initializer list in a quick and flexible way:

    {
      FIFTY1, FIFTY2,  // 1,1,1,1... 50 times, then 2,2,2,2... 50 times
      TWENTY3, EIGHTY4 // 3,3,3,3... 20 times, then 4,4,4,4... 80 times
      ... // and so on
    };
    
    0 讨论(0)
  • 2020-11-29 05:49

    One line with pointers!

    for (int *p = a; p < (a + 30); p++) *p = 1;
    

    Or if you're prematurely afraid of performance hit caused by repeatedly calculating (a + 30):

    for (int *p = a + 30 - 1; p >= a; p--) *p = 1;
    
    0 讨论(0)
  • 2020-11-29 05:52

    This is a GCC extension:

    int a[100] = {[0 ... 99] = 1};
    
    0 讨论(0)
提交回复
热议问题