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

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

提交回复
热议问题