O'Reilly logo

C Primer Plus, Fourth Edition by Stephen Prata

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required