【发布时间】:2018-04-06 23:17:28
【问题描述】:
我一直在研究和测试我的 C 知识(我是一名新计算机工程专业的学生),但遇到了一个我无法弄清楚的问题。
当尝试将二维数组传递给函数时,我了解到动态分配的数组不能这样做,因为编译器需要知道数组[][列]。但是,我了解到 2D 数组存储一个 1D 数组,其中每个新行的元素紧跟前一行的元素。当我将数组名称作为指向数组的指针传递给函数时,情况似乎就是这样,并且我的代码工作正常。但是,在声明 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 = 0; i < dimA[0]; ++i) {
for(j = 0; j < dimA[1]; ++j) {
printf("%3d", *(A[i] + j)); //This would work if the elements of A[] are pointers
}
printf("\n\n");
}
for(i = 0; i < dimA[0]; ++i) { //Same code as printArray function
for(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");
}
printArray(A, dimA);
return 0;
}
当数组被视为指针数组时,以下代码在 main() 中正确输出数组,但当被视为一维整数数组时则不正确。但是,当我将相同的数组作为指针传递给 printArray 函数时,我可以将其视为一维整数数组并且它可以工作。任何帮助将不胜感激(我已经明白我可以使用指针数组,但我真的很想了解问题所在)。谢谢!
【问题讨论】:
标签: arrays c pointers multidimensional-array implicit-conversion