使用C中的指针表达式迭代2D数组
发布时间:2020-12-16 09:54:29 所属栏目:百科 来源:网络整理
导读:我正在练习指针,并希望用指针操作代替数组来遍历数组的元素.我读了很多文章,无法掌握这个概念.谁能解释一下? 在这里,我创建了一个2D数组,并使用基本的嵌套for循环迭代它,但是想要使用指针; int test[3][2] = {1,4,2,5,8};for (int i = 0 ; i 3; i++) { for
我正在练习指针,并希望用指针操作代替数组来遍历数组的元素.我读了很多文章,无法掌握这个概念.谁能解释一下?
在这里,我创建了一个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("%dn",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("%dn",*p2); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |