CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Initializing 1-dimensional arrays

Like all variables, arrays should be initialized before we try to access their elements. We can:

  • initialize the elements at run-time, by executing statements to assign values to the elements:
    #define  N   5
    
    int   myarray[ N ];
    
    ....
    
        for(int i=0 ; i < N ; ++i) {
            myarray[ i ] = i;
        }
    

  • we may initialize the values at compile-time, by telling the compiler what values to initially store in the memory represented by the array. We use curly-brackets (braces) to provide the initial values:
    #define  N   5
    
    int   myarray[ N ] = { 0, 1, 2, 3, 4 };
    

  • we may initialize the values at compile-time, by telling the compiler what values to initially store in the memory represented by the array, and having the compiler determine the number of elements in the array(!).
    int   myarray[ ] = { 0, 1, 2, 3, 4 };
    
    #define  N   (sizeof(myarray) / sizeof(myarray[0]))
    

  • or, we may initialize just the first few values at compile-time, and have the compiler initialize the rest with zeroes:
    #define  HUGE   10000
    
    int   myarray[ HUGE ] = { 4, 5 };
    

 


CITS2002 Systems Programming, Lecture 5, p3, 5th August 2024.