Variable-Length Arrays (VLAs)

You might have noticed an oddity about functions dealing with two dimensional arrays: You can describe the number of rows with a function parameter, but the number of columns is built into the function. For example, look at this definition:

#define COLS 4
int sum2d(int ar[][COLS], int rows)
{
    int r;
    int c;
    int tot = 0;

    for (r = 0; r < rows; r++)
        for (c = 0; c < COLS; c++)
            tot += ar[r][c];
    return tot;
}

You can use it with any of the following function calls:

tot = sum2(array1, 5);   // sum a 5x4 array
tot = sum2(array2, 100); // sum a 100x4 array
tot = sum2(array3, 2);   // sum a 5 x 2 array

That's because the number of rows is passed to the rows parameter, a variable. But if you wanted to sum a 6x5 array, you would ...

Get C Primer Plus, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.