c - 在 C 中用指针表达式迭代二维数组

标签 c pointers

我正在练习指针,想用指针操作代替数组来遍历数组的元素。我看了很多文章,无法理解这个概念。谁能解释一下?

这里我制作了一个二维数组并使用基本的嵌套 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]);
    }
}

最佳答案

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);
    }
}

关于c - 在 C 中用指针表达式迭代二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26125746/

相关文章:

java - 保证TCP客户端和服务器之间不丢包

c - c中使用链表实现队列

c - 将字符串分配为结构成员时出现内存泄漏

崩溃问题,可能是由于 for 循环

c - 什么时候使用双指针?

c - 在 c 中设置自定义日期的问题

c - 使用 C (Ubuntu) 的套接字编程中的段错误

c++ - 将类成员函数作为参数传递

c++ - 如何在不使用 strcmp 和方括号的情况下比较字符串?

c - 如何使用 C 中的指针表示法和冒泡排序算法对函数中的数组进行排序