双指针试验2D数组

时间:2012-09-21 11:48:21

标签: c multidimensional-array double-pointer

我正在尝试使用双指针实现2D数组。我试图实现的是根据其物理表示来视觉化。例如,考虑一个2 x 2矩阵,其物理表示是

     c1  c2
     

R1 - > A00 A01
  R2 - > A10 A11

步骤1:创建指向第一行的双指针
第2步:创建指向c1地址的第一级指针 第3步:用户输入
步骤4:创建指向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中我得到了不稳定的结果。它开始指向其他位置

请您告诉我如何以我之前说过的方式实现这个2D阵列?我正在做这个练习 实验目的只是为了深入了解双指针的工作原理。

1 个答案:

答案 0 :(得分:0)

这一行:

printf("%d",*(p+j));

实际上将指针打印到行j(因为p指向行,而不是行元素)。您可以通过再解除引用来修复它:

printf("%d",p[i][j]));

并删除

 p += 1;

来自第二个循环。

此外,您的代码很难阅读,请尽量避免使用***temp并每隔一行重新分配指针。

相关问题