E
E
evg_962018-03-28 03:31:07
C++ / C#
evg_96, 2018-03-28 03:31:07

Why don't variable length arrays work?

In the book, I reached the chapter on arrays of variable length. I enter an example, but there are complaints that the parameter is not allowed. What is the problem please explain.
PS. VSC
Upd. Apparently the problem is in the compiler ... ( everything worked here )

#include <stdio.h>
#include <conio.h>

#define ROWS 3
#define COLS 4

int sum2d(int rows, int cols, int arr[rows][cols]); // Warning

int main(void)
{
    int arr[ROWS][COLS] = {
        { 2, 4, 6, 8 },
        { 3, 5, 7, 9 },
        { 12, 10, 8, 6 }
    };

    int i, j;
    int rs = 3;
    int cs = 10;

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

    int varr[rs][cs]; // Warning

    for (i = 0; i < rs; i++)
        for (j = 0; j < cs; j++)
            varr[i][j] = i * j + j;

    printf("Tradition array 3x5\n");
    printf("Sum of all items = %d\n", sum2d(ROWS, COLS, arr));

    printf("Tradition array 2x6\n");
    printf("Sum of all items = %d\n", sum2d(ROWS - 1, COLS + 2, arr));

    printf("Not tradition array 3x10\n");
    printf("Sum of all items = %d\n", sum2d(rs, cs, varr));

    _getch();

    return 0;
}

int sum2d(int rows, int cols, int arr[rows][cols]) // Warning
{
    int row, col;
    int total = 0;

    for (row = 0; row < ROWS; row++)
        for (col = 0; col < COLS; col++)
            total += arr[row][col];

    return total;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2018-03-28
@res2001

Support for VLA (and in general for all new language extensions) really depends on the compiler.
For example, in MSVC, in my opinion, there is still no VLA support.
Microsoft officially declares support for C90: https://docs.microsoft.com/en-us/cpp/c-language/an...
But the compiler contains language extensions (enabled by default), a list of extensions can be found in the option description /Zc compiler, and VLA is not there.
Despite the fact that there are some extensions from C ++ 17.
In addition, there are some things that appeared in C99, but they are not in "extensions", they are already included in the compiler "by default", for example, a variable number of arguments in #define.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question