错误左值作为赋值的左操作数返回 这个程序有什么错误;
int(*matrix)[row][col];
int i = 0;
if(n == 1)
{
for (int i = 0; i < no_matrices; i++)
{
printf("Matrix %d", i + 1);
(matrix + i) = GetMatrixU(row, col); // (error here)
}
}
int* GetMatrixU(int row, int col)
srand(time(NULL));
int(* matrix)[col] = malloc(col*sizeof(int));
for (int i = 0; i < row; i ++)
{
for (int j = 0; j < col; j ++)
{
matrix[i][j] = rand()%100;
}
}
return matrix[];
}
最佳答案
问题出在这一行:
(matrix + i) = GetMatrixU(row, col);
这会尝试进行分配。计算右边的表达式;这是“r 值”(“r”代表“正确”)。然后将结果赋给左边的表达式,即“l-value”(“l”代表“left”)。
嗯,(matrix + i)
不是有效的左值。矩阵本身是一个指向二维数组的指针。在 C 语言中,你不能只指定一个指针值并赋值给它;您必须使用 *
运算符来取消引用数组,并通过该数组进行分配。
这是一个简短的代码示例,展示了如何取消引用指针,然后重复您的错误。
main()
{
int a[10];
*(a + 1) = 0; // proper use of * to dereference
a + 1 = 0; // will not compile; error is "l-value required"
}
但在 C 中,有一种快捷方式可以添加到指针,然后取消引用它。它是方括号和索引值的使用:
a[1] = 0; // index the array
在 C 语言中,表达式 *(a + i)
和 a[i]
根据定义,含义完全相同。
http://en.wikipedia.org/wiki/C_syntax#Accessing_elements
看起来您正在尝试创建一个随机矩阵,一次一行。并且您正在为每一行分配内存。您的基本矩阵声明应该是指向行的指针数组。
int *matrix[rows];
for (i = 0; i < rows; ++i)
{
// either of these lines will work; pick just one
*(matrix + i) = AllocateRandomRow(cols); // explicit add-and-dereference
matrix[i] = AllocateRandomRow(cols); // simpler: just index array
}
我赞成使用第二种更简单的语法来解决这个问题。您正在索引一个数组;只需使用方括号即可。
这是一个免费的在线文本,描述如何动态分配矩阵。
关于c - 在c中返回多维指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24359256/