“表达式必须有一个常量值”visual studio 错误 E0028

Suk*_*hon 4 c visual-c++

#define max 40
...

void transpose(int matrix[][max], int* row, int* col)
{
    int data[*row][max]; //expression must have a constant value at *row.
    for (int i = 0; i < *row; i++)
    {
        for (int j = 0; j < *col; j++)
        {
            data[i][j] = matrix[i][j];
        }
    }
    int _col = *row; //this *row works fine.
    *row = *col; //also this *row works fine.
    *col = _col;
    for (int i = 0; i < *row; i++) //this *row is fine too.
    {
        for (int j = 0; j < *col; j++)
        {
            matrix[i][j] = data[j][i];
        }
    }
}

int main()
{
    ...
    if (...)
    {
        int row = 0, col = 0;
        int matrix[30][max];
        if (FunctionReadFile(Parameters[0], matrix, &row, &col))
        {
            ...
            transpose(matrix, &row, &col);
            ...
        }
        ...
    }
    ...
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我尝试在 int 之前放置 'const' 但它仍然在 [*row] 处显示此错误,为什么会发生此错误以及如何修复它?声明一个动态数组是否是解决这个问题的唯一方法,任何可能的解决方案更容易?

klu*_*utt 5

您的编译器不支持 VLA:s,因此您应该使用动态分配:

void transpose(int matrix[][max], int* row, int* col)
{
    // Parenthesis matters. This is a pointer to array of size max. Without
    // the parenthesis, it would be an array of pointers to int.
    int (*data)[max] = malloc(max * sizeof (*data)); 

    for (int i = 0; i < *row; i++)
    {
        for (int j = 0; j < *col; j++)
        {
            data[i][j] = matrix[i][j];
        }
    }

    free(data);
}
Run Code Online (Sandbox Code Playgroud)

请注意,我没有检查分配是否失败。您可以通过简单的检查来做到这一点。如果指针为 NULL,则分配失败。此外,请记住在完成后释放内存,如图所示。