use*_*901 2 c++ arrays double-pointer multidimensional-array
我不明白为什么我必须接收2D数组的内容b[][3]而不是 **b?另外我们如何才能为二维数组调用值?另外,2D阵列的地址arr等于内容的arr等于*arr等于&arr[0][0]; 所有地址都一样.我无法清楚地看清楚它; 有人可以向我解释如何实际存储多维数组."图片有用的链接将受到欢迎".
#include "hfile.h" // contains all needed H files
void caller(int b[][3]) // why can't we write **b?
{
int k=100;
printf("\n****Caller:****\n");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
b[i][j]=k++;
printf("\t %d",b[i][j]);
}
printf("\n");
}
}
int main()
{
int arr[3][3]={1,2,3,4,5,6,7,8,9}; // original containts
caller(arr); // Called caller function passing containts of "arr"
printf("\n****Orignal****\n");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
printf("\t %d",arr[i][j]);
printf("\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果声明一个多维数组:
int b[M][N];
Run Code Online (Sandbox Code Playgroud)
存储是连续的.因此,当您访问元素时,例如(x = b[i][j];),编译器会生成与此等效的代码:
int *c = (int *)b; // Treat as a 1D array
int k = (i*N + j); // Offset into 1D array
x = c[k];
Run Code Online (Sandbox Code Playgroud)
当您通过指针指向访问元素时,编译器不知道维度,它会生成如下代码:
int *t = b[i]; // Follow first pointer (produces another pointer)
x = t[j]; // Follow second pointer
Run Code Online (Sandbox Code Playgroud)
即它只是遵循指针.
这些是完全不兼容的,因此编译器会阻止您将真正的2D数组传递给采用指针指针的函数.
| 归档时间: |
|
| 查看次数: |
184 次 |
| 最近记录: |