0
我想实现一个使用双指针的二维数组。我试图实现的方式是根据其物理表示将其视觉化。例如,考虑一个2×2矩阵和它的物理表示是双指针实验二维数组
c1 c2
R1 - > A00 A01
R2 - > A10 A11
步骤1:创建一个双指针以指向到第一行
步骤2:创建第一级指针指向c1的地址步骤3:从用户输入
步骤4:创建第一级指针poi NT才能的C2
步骤5的地址:从用户
步骤6输入:递增行指针为指向R2
步骤7:从步骤重复2至5
下面是实现的代码的代码段由我:
int _tmain(int argc, _TCHAR* argv[])
{
int **p,***temp;
p = (int **)malloc(nRows*sizeof(int *));
//Allocating memory for two rows, now p points to R1
temp = &p; //storing the address of p to restore it after storing the values
for(int i=0;i<nRows;i++)
{
for(int j=0;j<nCols;j++)
{
*(p+j) = (int *)malloc(sizeof(int));
//Allocating memory for col , now *p points to C1
scanf("%d",*(p+j));
}
p += 1; // NOw p is pointing to R2
}
p = *temp; // restoring the base address in p;
for(int i=0;i<nRows;i++)
{
for(int j=0;j<nCols;j++)
printf("%d",*(p+j));
// In first iteration print values in R1 and R2 in second iteration
p += 1; // points to the next row
}
getch();
return 0;
}
该scanf似乎工作正常。但在printf中,我得到了不稳定的结果。它开始指向一些其他的位置
你能让我知道如何以前面说过的方式实现这个二维数组吗?我正在练习 这个练习,目的只是为了深入了解双指针的工作。
我是新来的编程和尝试学习..所以请帮助 – user1611753
开始理解简单的1D数组,以及数组和指针之间的关系或非关系... –
这里有一个链接,你需要什么知道:http://stackoverflow.com/questions/12462615/how-do-i-correctly-set-up-access-and-free-a-multidimensional-array-in-c – Mike