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

时间:2015-07-27 18:43:52

标签: c arrays function argument-passing

这是我在普通老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中得到以下错误/警告,这自然会导致我的代码崩溃。我应该如何将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 )
     ^

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我将此作为XY problem回答,因为您想要对列进行求和,并且这样做会遇到其他问题,您会问如何解决这些问题。但也是我不得不猜测的不完整信息的答案。

您声明了一个2D数组short rawdata[][20],但提供的数据就好像它是一维数组一样。然后你摆弄指针并提出错误的答案。

此答案正确初始化2D数组,并使用数组索引简单地对列进行求和。

#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