P
P
polger2019-01-24 20:33:53
C++ / C#
polger, 2019-01-24 20:33:53

Why doesn't the example from The C Programming Language 6th edition by Stephen Prat work?

Question about arrays of variable length.
Here's an example from the book:

//vararr2d.c -- функции, использующие массивы переменной длины
#include <stdio.h>
#define ROWS 3
#define COLS 4
int sum2d(int rows, int cols, int ar[rows][cols]);
int main(void)
{
    int i, j;
    int rs = 3;
    int cs = 10;
    int junk[ROWS][COLS] = {
        {2,4,6,8},
        {3,5,7,9},
        {12,10,8,6}
    };

    int morejunk[ROWS-1][COLS+2] = {
        {20,30,40,50,60,70},
        {5,6,7,8,9,10}
    };

    int varr[rs][cs]; // массив переменной длины
    for (i = 0; i < rs; i++)
        for (j = 0; j < cs; j++)
            varr[i][j] = i * j + j;

    printf("Традиционный массив 3x5\n");
    printf("Сумма всех элементов = %d\n",
            sum2d(ROWS, COLS, junk));

    printf("Традиционный массив 2x6\n");
    printf("Сумма всех элементов = %d\n",
            sum2d(ROWS-1, COLS+2, morejunk));

    printf("Массив переменной длины 3x10\n");
    printf("Сумма всех элементов = %d\n",
            sum2d(rs, cs, varr));

    return 0;
}

// функция с параметром типа массива переменной длины
int sum2d(int rows, int cols, int ar[rows][cols])
{
    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;
}

I'm using the latest Visual Studio.
1. I guess that for arrays of variable length it is necessary to allocate memory manually. This is true?
2. Why does VS disagree with this code? In particular, in the prototype int sum2d(int rows, int cols, int ar[rows][cols]); and defining the function int sum2d(int rows, int cols, int ar[rows][cols]) underlines rows and cols?
3. Why the author declares a multidimensional array using non-constant values ​​in the line: int varr[rs][cs]; // variable length array ?
Are all these remarks a feature of the compiler from Microsoft or is there a problem in something else?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pfemidi, 2019-01-24
@polger

It won't work in Visual Studio, VS can't C99.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question