在c中返回多维指针
错误左值作为赋值的左操作数返回 这个程序有什么错误在c中返回多维指针,c,C,错误左值作为赋值的左操作数返回 这个程序有什么错误 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
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[];
}
int(*矩阵)[行][col];
int i=0;
如果(n==1)
{
对于(int i=0;i
以下是一个简单案例的示例,以了解这个更复杂的案例:
int b = 4;
int *a = &b; // Allowed and works because a is a pointer to an integer
a+1 = 5; // Not allowed no idea about the type of a+1 and it could be used!!
为什么这与你的问题有关
int(*matrix)[5][5];
printf("%p\n",matrix);
printf("%p\n",matrix+1);
输出
0xb7753000
0xb7753064
上述指针之间的差值为6*16+4=100。这个数字就是row*col*sizeOf(int)=5*5*4=100
因此,您要做的是访问矩阵中的单元,而实际上您要做的是尝试访问一个不允许您使用的内存,如第一个简单示例中所示
您实际在做什么与您希望程序做什么的示例:
int(*matrix)[5][5];
matrix + 0 => address of matrix
matrix + 1 => address of matrix + 100 bytes (you expected + 4 bytes instead)
matrix + 2 => address of matrix + 200 bytes (you expected + 8 bytes instead)
etc...
问题在于这一行:
(matrix + i) = GetMatrixU(row, col);
这是一个任务。对右侧的表达式进行求值;这是“r值”(“r”代表“权利”)。然后将结果分配给左边的表达式,即“l值”(“l”表示“左”)
嗯,(矩阵+i)
不是有效的l值<代码>矩阵本身是指向二维数组的单个指针。在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]
的含义完全相同
看起来您正试图创建一个随机矩阵,一次一行。您正在为每一行分配内存。基本矩阵声明应该是指向行的指针数组
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
}
int*矩阵[行];
对于(i=0;i
我支持第二种更简单的语法来解决这个问题。您正在为数组编制索引;只需使用方括号
这里是一个免费的在线文本,描述了如何动态分配矩阵
错误在哪一行?发布一个包含错误的完整(但很小)程序。没有提供足够的信息来诊断真正的问题是最直接的错误。没有分配足够的空间在某种程度上是次要的。语法错误只是伤口上的盐代码>与
int*矩阵[行][col]相同代码>?@Amir不,不是。前者是指向数组数组的单指针,后者是指针数组。感谢您的澄清,我认为是一样的,我将作为指向int的指针数组数组来回答