【问题标题】:pointer issues in C++, not traversing correctly [closed]C ++中的指针问题,无法正确遍历[关闭]
【发布时间】:2016-05-05 01:57:28
【问题描述】:
    int main()
{
    const int x = 4;
    int row, col, j;
    int myArray[x][x], *xptr;


    for (row = 0; row < 4; row++){
        for (col = 0; col < 4; col++){
            myArray[row][col] = (row * 4) + col;
        }
    }

    printf("contents of myArray... \n");

    /* set xptr to the front of myArray*/
    xptr = &(myArray[0][0]);

    /*Print out the contents of the array. */
    for (row = 0; row < 4; row++) {
        for (col = 0; col < 4; col++) {
            printf("%d ", *(xptr + (row * 4) + col));
        }
    }
    printf("\n");

    /* Print out contents again, this time increment the pointer. */
    printf(" Contents of the x array again... \n");

    /* Set xptr to the front of the x array. */

    xptr = &(myArray[0][0]);

    /*print out the contents of the array. */


        for (j = 0; j< 16; j++);

        printf("%d ", *xptr);

        xptr++;
    }
    }

我无法使用指针作为打印地址来重新打印数组。 IE,根据我的教授笔记我应该得到 x 数组的内容...

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

又是 x 数组的内容...

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

但是我得到了

contents of myArray...
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
contents of the x array again...
0

然后就结束了。我试过玩所有东西,但我不确定是什么给了我这个错误

谢谢, 哭泣者

【问题讨论】:

  • 这就是正确的代码格式至关重要的原因——你应该真正尝试在缩进方面使事物匹配,以便快速轻松地发现不匹配的大括号等。

标签: c++ pointers multidimensional-array


【解决方案1】:
    for (j = 0; j< 16; j++);

看到行尾多余的分号了吗?

对于第二个循环,您的大括号似乎也不正确。

【讨论】:

  • 哦,天哪,我是不是觉得很笨 :( 非常感谢我删除了多余的分号,但是我找不到你在说的括号问题?而且,它打印出了 myArray 的内容...... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 x 数组的内容再次... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  • 如果您正确缩进代码,您可能会发现大括号问题。这段代码的缩进是一团糟。到处都是。由于某种原因,“int main()”缩进了四个空格;然后,在下一行,第一个左大括号莫名其妙地移动到左边距。显示代码的最后两行有右大括号,都在相同的缩进级别,等等……等等……等等……大多数编辑器都具有自动正确缩进代码的功能。学习使用它们。
猜你喜欢
  • 2013-09-12
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-29
  • 1970-01-01
相关资源
最近更新 更多