简体   繁体   English

如何将二维数组写入C中的指针

[英]How to write two dimensional array into pointers in C

I have a two dimensional array.我有一个二维数组。

int32_t B[N][M];
for (int i = 0; i < N + 1; i++)
    {
        for (int j = 0; j < M; j++)
        {
            some_function(B[i][j]);
            some_func1(B[i][j], p1);
        }
    }

I am converting it to pointer.我正在将其转换为指针。

int32_t *B;
 for (int n=0; n<N+1; n++) {
        for (int m=0; m<M; m++)
        {
            some_function(B[n*M+m]);
            some_func1(B[n*M+m], p); 
        }
    }

I want some clarification on how B[n][m] converted to B[n*M+m] and How to access subsequent array elements like B[1][1] in that case?我想澄清一下B[n][m]如何转换为B[n*M+m]以及在这种情况下如何访问像B[1][1]这样的后续数组元素?

I have 3-dimensional array to convert to pointers too.我也有要转换为指针的 3 维数组。 Any help and tips will be appreciated.任何帮助和提示将不胜感激。

If your compiler supports Variable Length Arrays, this could be used.如果您的编译器支持可变长度 Arrays,则可以使用它。
This allows access to the array as B[row][col] .这允许以B[row][col]的形式访问数组。

#include <stdio.h>
#include <stdlib.h>

int main ( void) {
    int N = 3;
    int M = 7;
    int32_t (*B)[M] = NULL; // pointer to Variable Length Array

    if ( NULL == ( B = malloc ( sizeof *B * N))) {
        fprintf ( stderr, "malloc problem\n");
        return 1;
    }
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            some_function(B[i][j]);
            some_func1(B[i][j], p1);
        }
    }
    free ( B);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM