访问C中多维指针数组中的特定元素

时间:2017-09-16 09:36:49

标签: c pointers multidimensional-array indexing

如何在i行和j列的2D数组中访问元素0-K? 我无法看到如何使用嵌套for循环来索引所需的元素将起作用,因为不知道K是小于还是大于i或j。

所以,我认为有必要提供不同的条件:

if (K < j) {
     //index through the first row
    }

while (K > j) {
     //do some manipulations to determine how many rows to index through 
     }

但这似乎不必要地复杂。有没有办法使用指针和derefencers从2D数组指针中获取元素K的值?

比如说,我想从这个数组中得到值7:
image.

(注意:此图像无法准确反映指针的2D数组的外观......我知道这实际上是一维数组的数组。)

1 个答案:

答案 0 :(得分:0)

如果我理解正确,那么您需要以下内容。

首先,您可以将二维数组重新解释为一维数组。您可以将顺序索引拆分为行和列。

在下面的示范程序中,显示了这两种方法。

#include <stdio.h>

#define M   3
#define N   4

int main(void) 
{
    int a[M][N];

    int *p = ( int * )a;

    for ( size_t i = 0; i < M * N; i++ )
    {
        p[i] = i;
    }

    for ( size_t i = 0; i < M * N; i++ )
    {
        printf( "%2d ", a[ i / N ][ i % N ] );
        if ( ( i + 1 ) % N == 0 ) putchar( '\n' );
    }

    return 0;
}

程序输出

 0  1  2  3 
 4  5  6  7 
 8  9 10 11