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

后端 未结 23 1908
清歌不尽
清歌不尽 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:17

    I see no requirements in the question, so the solution must be generic: initialization of an unspecified possibly multidimensional array built from unspecified possibly structure elements with an initial member value:

    #include  
    
    void array_init( void *start, size_t element_size, size_t elements, void *initval ){
      memcpy(        start,              initval, element_size              );
      memcpy( (char*)start+element_size, start,   element_size*(elements-1) );
    }
    
    // testing
    #include  
    
    struct s {
      int a;
      char b;
    } array[2][3], init;
    
    int main(){
      init = (struct s){.a = 3, .b = 'x'};
      array_init( array, sizeof(array[0][0]), 2*3, &init );
    
      for( int i=0; i<2; i++ )
        for( int j=0; j<3; j++ )
          printf("array[%i][%i].a = %i .b = '%c'\n",i,j,array[i][j].a,array[i][j].b);
    }
    

    Result:

    array[0][0].a = 3 .b = 'x'
    array[0][1].a = 3 .b = 'x'
    array[0][2].a = 3 .b = 'x'
    array[1][0].a = 3 .b = 'x'
    array[1][1].a = 3 .b = 'x'
    array[1][2].a = 3 .b = 'x'
    

    EDIT: start+element_size changed to (char*)start+element_size

提交回复
热议问题