c - 为什么我们不能像一维数组一样访问二维数组?我怎样才能访问?

标签 c arrays pointers

为什么我们不能像一维数组一样访问二维数组?我怎样才能访问?

数组函数:

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/

相关文章:

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c - 输出参数中带有指向对象的指针的动态数组

c++ - 为什么将 COM 指针参数强制转换为 void 而不是 IUnknown?

C++ string.compare()

mysql - 错误 : token "@" is not valid in preprocessor expressions

C : Converting all special char to the equivalent (é => e)

javascript - 如何从拆分数组函数中乘以数据

pointers - 在指针接收器上调用 Elem() 方法以进行结构反射的必要性

c++ - c 问题错误在此函数中使用统一化

c - 如果缺少 const char* 数组初始化逗号,则生成编译器警告