使用C中的指针表达式迭代2D数组

rya*_*yan 3 c pointers

我正在练习指针,并希望用指针操作代替数组来遍历数组的元素.我读了很多文章,无法掌握这个概念.谁能解释一下?

在这里,我创建了一个2D数组,并使用基本的嵌套for循环迭代它,但是想要使用指针;

int test[3][2] = {1,4,2,5,2,8};

for (int i = 0 ; i < 3; i++) {

    for (int j = 0; j < 2; j++) {

        printf("%d\n", test[i][j]);
    }
}
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 7

int test[3][2] = {{1,4},{2,5},{2,8}};

// Define a pointer to walk the rows of the 2D array.
int (*p1)[2] = test;

// Define a pointer to walk the columns of each row of the 2D array.
int *p2 = NULL;

// There are three rows in the 2D array.
// p1 has been initialized to point to the first row of the 2D array.
// Make sure the iteration stops after the third row of the 2D array.
for (; p1 != test+3; ++p1) {

    // Iterate over each column of the arrays.
    // p2 is initialized to *p1, which points to the first column.
    // Iteration must stop after two columns. Hence, the breaking
    // condition of the loop is when p2 == *p1+2
    for (p2 = *p1; p2 != *p1+2; ++p2 ) {
        printf("%d\n", *p2);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 一些解释很适合你的答案。但是,对于完全指针驱动的方法,1+... :-) (2认同)