小编Nat*_*ows的帖子

为什么二维数组的行为类似于一维指针数组而不是一维整数数组?

我一直在研究和测试我在 C 方面的知识(我是一名新的计算机工程专业的学生),遇到了一个我无法弄清楚的问题。

在尝试将 2D 数组传递给函数时,我了解到您不能使用动态分配的数组这样做,因为编译器需要知道 array[][columns]。但是,我了解到二维数组存储在一维数组中,其中每个新行的元素都跟在前一行的元素之后。当我将数组名称作为指向数组的指针传递给函数时,情况似乎如此,我的代码运行良好。但是,在声明 2D 数组的函数中,它表现为一个指针数组。

#include <stdio.h>

void printArray(int *A, int* dimA) {
    for(int i = 0; i < dimA[0]; ++i) {
        for(int j = 0; j < dimA[1]; ++j) {
            printf("%3d", A[i*dimA[1] + j]);//This would work if the elements of A[] are the rows of a 2D array mapped into a 1D array
        }
    printf("\n\n");
    }
return;
}

int main(){
    int A[2][2] = {{1,2},{3,4}};
    int dimA[2] = {2,2};//dimensions of the array
    int i, j; 

    for(i …
Run Code Online (Sandbox Code Playgroud)

c arrays pointers multidimensional-array implicit-conversion

2
推荐指数
1
解决办法
563
查看次数