gpt4 book ai didi

c - "expression must have a constant value" Visual Studio 错误 E0028

转载 作者:行者123 更新时间:2023-12-03 10:14:37 26 4
gpt4 key购买 nike

#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;
}

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

最佳答案

您的编译器不支持 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);
}

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

关于c - "expression must have a constant value" Visual Studio 错误 E0028,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58975523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com