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

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

    You can do the whole static initializer thing as detailed above, but it can be a real bummer when your array size changes (when your array embiggens, if you don't add the appropriate extra initializers you get garbage).

    memset gives you a runtime hit for doing the work, but no code size hit done right is immune to array size changes. I would use this solution in nearly all cases when the array was larger than, say, a few dozen elements.

    If it was really important that the array was statically declared, I'd write a program to write the program for me and make it part of the build process.

    0 讨论(0)
  • 2020-11-21 05:12

    Cutting through all the chatter, the short answer is that if you turn on optimization at compile time you won't do better than this:

    int i,value=5,array[1000]; 
    for(i=0;i<1000;i++) array[i]=value; 
    

    Added bonus: the code is actually legible :)

    0 讨论(0)
  • 2020-11-21 05:14

    I know that user Tarski answered this question in a similar manner, but I added a few more details. Forgive some of my C for I'm a bit rusty at it since I'm more inclined to want to use C++, but here it goes.


    If you know the size of the array ahead of time...

    #include <stdio.h>
    
    typedef const unsigned int cUINT;
    typedef unsigned int UINT;
    
    cUINT size = 10;
    cUINT initVal = 5;
    
    void arrayInitializer( UINT* myArray, cUINT size, cUINT initVal );
    void printArray( UINT* myArray ); 
    
    int main() {        
        UINT myArray[size]; 
        /* Not initialized during declaration but can be
        initialized using a function for the appropriate TYPE*/
        arrayInitializer( myArray, size, initVal );
    
        printArray( myArray );
    
        return 0;
    }
    
    void arrayInitializer( UINT* myArray, cUINT size, cUINT initVal ) {
        for ( UINT n = 0; n < size; n++ ) {
            myArray[n] = initVal;
        }
    }
    
    void printArray( UINT* myArray ) {
        printf( "myArray = { " );
        for ( UINT n = 0; n < size; n++ ) {
            printf( "%u", myArray[n] );
    
            if ( n < size-1 )
                printf( ", " );
        }
        printf( " }\n" );
    }
    

    There are a few caveats above; one is that UINT myArray[size]; is not directly initialized upon declaration, however the very next code block or function call does initialize each element of the array to the same value you want. The other caveat is, you would have to write an initializing function for each type you will support and you would also have to modify the printArray() function to support those types.


    You can try this code with an online complier found here.

    0 讨论(0)
  • 2020-11-21 05:17

    For delayed initialization (i.e. class member constructor initialization) consider:

    int a[4];
    
    unsigned int size = sizeof(a) / sizeof(a[0]);
    for (unsigned int i = 0; i < size; i++)
      a[i] = 0;
    
    0 讨论(0)
  • 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 <string.h> 
    
    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 <stdio.h> 
    
    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

    0 讨论(0)
  • 2020-11-21 05:19

    Here is another way:

    static void
    unhandled_interrupt(struct trap_frame *frame, int irq, void *arg)
    {
        //this code intentionally left blank
    }
    
    static struct irqtbl_s vector_tbl[XCHAL_NUM_INTERRUPTS] = {
        [0 ... XCHAL_NUM_INTERRUPTS-1] {unhandled_interrupt, NULL},
    };
    

    See:

    C-Extensions

    Designated inits

    Then ask the question: When can one use C extensions?

    The code sample above is in an embedded system and will never see the light from another compiler.

    0 讨论(0)
提交回复
热议问题