【问题标题】:Double pointer experimenting with 2D array双指针实验二维数组
【发布时间】:2012-09-21 11:48:20
【问题描述】:

我正在尝试使用双指针实现二维数组。我试图实现的方法是根据其物理表示对其进行可视化。例如,考虑一个 2 x 2 矩阵,其物理表示为

     c1  c2

R1 -> A00 A01
R2 -> A10 A11

第 1 步:创建指向第一行的双指针
第二步:创建指向c1地址的一级指针
第 3 步:用户输入
第四步:创建指向c2地址的一级指针
第 5 步:用户输入
第 6 步:将 Row 指针递增到点 R2
第 7 步:重复第 2 步到第 5 步

下面是我实现的代码sn-p:

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 我得到不稳定的结果。它开始指向其他位置

你能告诉我如何按照我之前所说的方式实现这个二维数组吗?我正在做这个练习 实验目的只是为了深入了解双指针的工作原理。

【问题讨论】:

  • 我是编程新手并正在努力学习。所以请帮忙
  • 从了解简单的一维数组以及数组和指针之间的关系或非关系开始...
  • 这里有一个你需要知道的链接:stackoverflow.com/questions/12462615/…

标签: c multidimensional-array double-pointer


【解决方案1】:

这一行:

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

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

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

并删除

 p += 1;

来自第二个循环。

另外,你的代码很难阅读,尽量避免***temp 和每隔一行重新分配指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多