为什么我们不能像一维数组一样访问二维数组?我怎样才能访问?
数组函数:
int **combination(int no)
{
int i,j,c=0;
static int arr[100][2];
for(i=0;i<=no;i++){
for(j=0;j<=no;j++){
if(((i+j)==no)){
arr[c][0]=i;
arr[c][1]=j;
c++;
}
}
}
return arr;
}
主要功能:
int main() {
int n,k,i;
int **arr;
int size=10;//let us assume.
scanf("%d %d", &n, &k);
fprintf(stderr, "1\n");
arr=combination(n);
fprintf(stderr, "2\n");
for(i=0;i<size;i++){
printf("%d-%d",arr[i][0],arr[i][1]);
}
return 0;
}
显示:
.c:29:8: warning: return from incompatible pointer type [-Wincompatible-pointer-types]
return arr
并且段错误核心已转储。
您能否建议调用什么指针类型来访问该二维数组中的元素?
最佳答案
这是因为 int arr[100][2]
(指向 int [2] 数组的指针)与 int**< 不兼容
(指向 int 的指针)。
为什么?
C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)
Array pointer conversion
(p3) Except when it is the operand of the
sizeof
operator, the_Alignof
operator, or the unary'&'
operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue.
将 6.3.2.1(p3) 应用于 int arr[100][2]
,结果为 int (*arr)[2]
(a指向 int [2] 数组的指针,该数组不是 int**
。因此您的编译器会正确生成警告。
如果您确实想这样做,请在 main()
中将 arr
声明更改为:
int (*arr)[2];
然后将函数声明更改为:
int (*(combination)(int no))[2]
(一个函数,采用(int no)
返回int(*...)[2]
指向数组的指针int
[2])
您还应该将函数中的 c
值限制为小于 100
,以防止超出数组范围。
关于c - 为什么我们不能像一维数组一样访问二维数组?我怎样才能访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59606807/