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

时间:2014-09-30 16:32:00

标签: 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]);
    }
}

5 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

尝试以下内容并进行调查

#include <stdio.h>

int main(void) 
{
    int test[3][2] = { { 1,4 }, { 2,5 }, { 2,8 } };

    for ( int ( *p )[2] = test ; p != test + 3; ++p ) 
    {
        for ( int *q = *p; q != *p + 2; ++q ) printf( "%d ", *q );
        puts( "" );
    }

    return 0;
}   

投入是

1 4 
2 5 
2 8

第一个指针是指向int[2]类型的对象的指针,它指向第一个&#34;行&#34;数组的然后由于增量它指向其他行..第二个指针是指向类型int的对象的指针。它指向内循环中每行的第一个元素。

答案 2 :(得分:0)

如果指针声明是练习的目标,请使用以下初始化:

int (*pTest)[rmax][cmax] = test;

一旦这样做,使用指针索引的语法镜像了数组索引的语法,除了你必须使用*去引用运算符。

for (int i= 0; i < 3; i++) { 
  for (int j= 0; j < 2; j++) {
     printf ("%d ", *(pTest[i][j])); 
  }
  printf ("\n"); 
}

但是,如果指针算术是您练习的目标,那么以下内容也会起作用:

int *res = &test;
for (int i = 0; i < 3; i++) {
  for (int j = 0; j < 2; j++) {
    printf ("%d ", *(res + i*2 + j)); 
  }
  printf ("\n"); 
}

<强>输出

1 4  
2 5  
2 8

答案 3 :(得分:0)

在某些编译器中,您还可以使用单个循环,将多维数组视为以行主顺序读取的一维数组。

King's C Programming: A Modern Approach(第2版,第268页)中提到了这一点。

#include <stdio.h>

int main(void)
{
    int test[3][2] = {{1,4},{2,5},{2,8}}, *p;

    for(p = &test[0][0]; p <= &test[2][1]; p++)
    {
        printf("%d\n", *p);
    }
    return 0;
}

答案 4 :(得分:0)

使用指针算法迭代将2d数组作为1d数组进行处理非常容易。

void print_2d_array(int *num, size) {
    int counter = 0;
    while (counter++ < size) {
        printf("%i ", *num);
        num++;
    }
    printf("\n");
}

int main() {
    int matrix[2][3] = {{2, 11, 33},
                       {9, 8,  77}};

    int matrix_size = sizeof(matrix) / sizeof(int); // 24 bytes / 4 (int size) = 6 itens 

    print_2d_array(matrix, matrix_size);

    return 0;
}
相关问题