C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用C中的指针表达式迭代2D数组大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在练习指针,并希望用指针操作代替数组来遍历数组的元素.我读了很多文章,无法掌握这个概念.谁能解释一下?

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

int test[3][2] = {1,4,2,5,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},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中的指针表达式迭代2D数组全部内容,希望文章能够帮你解决使用C中的指针表达式迭代2D数组所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。