CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Variable-length arrays

All of the examples of 1-dimensional arrays we've seen have the array's size defined at compile time:

#define  N   5

int   global_array[ N ];
....

    for(int i=0 ; i < N ; ++i) {
        int   array_in_block[ 100 ];
        ....
    }

As the compiler knows the exact amount of memory required, it may generate more efficient code (in both space and time) and more secure code.

More generally, an array's size may not be known until run-time. These arrays are termed variable-length arrays, or variable-sized arrays. However, once defined, their size cannot be changed.

In all cases, variable-length arrays may be defined in a function and passed to another. However, because the size is not known until run-time, the array's size must be passed as well. It is not possible to determine an array's size from its name.

void function2(int array_size, char vla[ ])
{
    for(int i=0 ; i < array_size ; ++i) {
        // access vla[i] ...
        ....
    }
}

void function1(void)
{
    int size = read an integer from keyboard or a file;

    char vla[ size ];

    function2(size, vla);
}

Variable-length arrays were first defined in the C99 standard, but then made optional in C11 - primarily because of their inefficient implementation on embedded devices. Modern Linux operating system kernels are now free of variable-length arrays.

 


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