如何将二维数组传递给 C 函数

How to pass a 2-dimensional array to a C function

这是我用普通的旧 C 编写的代码。我想添加数据的每一列。比如28+518+917, 34+512+914, et.al.:

short rawdata[][20]={
28,34,36,39,42,47,37,41,41,33,33,36,36,36,27,27,24,31,29,26,
518,512,507,508,521,522,524,525,519,512,506,511,511,501,501,495,497,500,508,504,
917,914,905,909,892,879,869,873,876,877,875,870,883,893,893,884,881,882,885,888
};

int aae( int nLenFrame, short **psDataBuffer, float *pFV )
{
    float sum = 0.0;
    int i=0, j;
    for (j=0; j<AXES; j++)
    {
        printf("Component: %d\n", *(*(psDataBuffer +j) + i));
    }
    return 1;
}


int main(int argc, char *argv[]){
    int arraySize;
    float pFV;
    int a;

    arraySize = sizeof(rawdata)/sizeof(int);
    a = aae( arraySize, rawdata, &pFV );
    printf("aae = %f\n", pFV);
}

我试图将 rawdata 传递给函数 aae,但是当我编译时,我从 gcc 得到以下 errors/warnings,这自然会导致我的代码崩溃。我应该如何将 rawdata 传递给 aae

$ gcc aae.c -o aae
aae.c: In function ‘main’:
aae.c:31:2: warning: passing argument 2 of ‘aae’ from incompatible pointer type [enabled by default]
  a = aae( arraySize, rawdata, &pFV );
  ^
aae.c:13:5: note: expected ‘short int **’ but argument is of type ‘short int (*)[20]’
 int aae( int nLenFrame, short **psDataBuffer, float *pFV )
     ^

在此先感谢您的帮助。

我以 XY problem 的形式回答这个问题,因为您想对列求和,这样做会遇到其他问题,您会问如何解决这些问题。但也有我不得不猜测的不完整信息的答案。

您声明了一个二维数组 short rawdata[][20] 但提供的数据就好像它是一个一维数组一样。然后你 fiddle 得到了指点并得出了一个错误的答案。

这个答案正确地初始化了一个二维数组,并通过使用数组索引简单地对列求和。

#include <stdio.h>

#define AXES 3
#define COLS 20

short rawdata[AXES][COLS]={
    {28,34,36,39,42,47,37,41,41,33,33,36,36,36,27,27,24,31,29,26 },
    {518,512,507,508,521,522,524,525,519,512,506,511,511,501,501,495,497,500,508,504},
    {917,914,905,909,892,879,869,873,876,877,875,870,883,893,893,884,881,882,885,888}
};

void sumcols(short rawdata[][COLS]) {
    int col, axis;
    float sum;

    for (col=0; col<COLS; col++) {
        sum = 0;
        for (axis=0; axis<AXES; axis++) {
            sum += rawdata [axis][col];
        }
        printf("Column %2d sum = %f\n", col, sum);
    }
}

int main(void) {
    sumcols(rawdata);
    return 0;
}

程序输出:

Column  0 sum = 1463.000000
Column  1 sum = 1460.000000
Column  2 sum = 1448.000000
Column  3 sum = 1456.000000
Column  4 sum = 1455.000000
Column  5 sum = 1448.000000
Column  6 sum = 1430.000000
Column  7 sum = 1439.000000
Column  8 sum = 1436.000000
Column  9 sum = 1422.000000
Column 10 sum = 1414.000000
Column 11 sum = 1417.000000
Column 12 sum = 1430.000000
Column 13 sum = 1430.000000
Column 14 sum = 1421.000000
Column 15 sum = 1406.000000
Column 16 sum = 1402.000000
Column 17 sum = 1413.000000
Column 18 sum = 1422.000000
Column 19 sum = 1418.000000