c - 将数组结构传递给函数

标签 c arrays struct moving-average

我正在尝试传递二维数组的结构并对它们进行计算。

typedef struct{
    float X[80][2];
    float Y[80][2];
    float Z[80][2];
    int T[80][2];
    int K[80];
} STATS;

void MovingAverage(STATS *stat_array, int last_stat) {
    //Average = Average(Prev) + (ValueToAverage/n) - (Average(Prev)/n)
    stat_array->**X**[last_stat][0] =  stat_array->**X**[last_stat][0] +
        (stat_array->**X**[last_stat][1] / stat_array->T[last_stat][0]) -
        (stat_array->**X**[last_stat][0] / stat_array->T[last_stat][0]);
}

调用函数:

MovingAverage(*stat_array, last_stat);

我的问题是:

如何以通用方式访问 MovingAverage 函数中的 X Y 和 Z?

<小时/>

编辑:

void MovingAverage(STATS *stat_array, int last_stat, (char *(array_idx)) { 
//Average = Average(Prev) + (ValueToAverage/n) - (Average(Prev)/n)
    stat_array->**array_idx**[last_stat][0] = 
                stat_array->**array_idx**[last_stat][0] + 
                (stat_array->**array_idx**[last_stat][1] / 
                stat_array->T[last_stat][0]) - 
                (stat_array->**array_idx**[last_stat][0] / 
                stat_array->T[last_stat][0]); 
}

我知道不行,但只是为了表明我的意愿,

最佳答案

这里的某人(不是我)可能会想出一些预处理器魔法来完成您所要求的操作,但这是我不会追求的解决方案。我认为这是不好的做法,因为宏很快就会变得繁琐且难以调试。如果有意义的话,您的源代码中不能有“变量”。在构建过程中,首先运行的事情之一是预处理器,它解析所有宏。然后它将源代码传递给编译器。编译器不会为您进行任何文本替换,它会根据其拥有的源代码进行操作。要实现您想要的效果,请编写一个对您想要的类型进行操作的函数,并使用您的所有类型调用该函数。我会将您的 MovingAverage 函数更改为如下所示:

void MovingAverage(float arr[80][2], const int T[80][2], int last_stat)
{
  arr[last_stat][0] = ... // whatever calculation you want to do here
}

int main(void)
{
  STATS stat_array;
  int last_stat;
  // .. initialize stat_array and last_stat

  // now call MovingAverage with each of your 3 arrays
  MovingAverage(stat_array.X, stat_array.T, last_stat);
  MovingAverage(stat_array.Y, stat_array.T, last_stat);
  MovingAverage(stat_array.Z, stat_array.T, last_stat);

  ...
  return 0;
}

关于c - 将数组结构传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49560884/

相关文章:

generics - 比较通用结构类型

c++ - 如何将编译选项传播到 CMake 中的子目录?

java - 从字符串数组中删除空元素,其中 "All elements are null"

PHP数组循环+MySQL数据

php - json_decode 未通过 curl 调用返回正确的 api 响应 php 数组

c - 我不明白这个 C 代码的行为(与 2 个位域结构、一个字和一个字节数组的 union )

c - 用 8 位整数替换部分 16 位整数

c - 如何在 Mac 中使用 bash 终端使用 c 程序获取修改后的环境变量

c - Valgrind:无效读取和使用未初始化值

c++ - 手动指定发送数据的网络接口(interface)