C 在循环中分配列表

C 在循环中分配列表,c,C,我有以下函数来获取某些点之间的距离: #include <stdio.h> #include <math.h> int add_coords(size_t size, float coords[size][2]) { float distance = 0; for (int i=0; i < size-1; i++) { float this[2] = coords[i]; // not allowed float

我有以下函数来获取某些点之间的距离:

#include <stdio.h>
#include <math.h>

int add_coords(size_t size, float coords[size][2])
{
    float distance = 0;
    for (int i=0; i < size-1; i++) {
        float this[2] = coords[i]; // not allowed
        float next[2] = coords[i+1];
        distance = sqrt(pow(this[0] - next[0]),2) + pow(this[1] - next[1]),2));
    }
    return distance;
}
int main(void)
{
    float coords[][2] = {{1,3}, {5,7}, {-2,-3}};
    float distance = add_coords(sizeof coords / sizeof *coords, coords);
    
    printf("The distance is %.2f\n", distance);
}
目前我正在做的是,这是一个有点棘手的想出:

// pointer to array of two
float (*this)[2], (*next)[2];

for (int i=0; i < size; i++) {
    this = &coords[i];
    next = &coords[i+1];
    distance += sqrtf(powf((*this)[0] - (*next)[0],2) + powf((*this)[1] - *(next)[1],2));
}
//指向两个数组的指针
浮动(*本)[2],(*下一个)[2];
对于(int i=0;i
我只需使用结构,这将避免任何不必要的未定义行为:

typedef结构坐标{
浮动x;
浮动y;
}图库兹
// ...
t_coords coords={.x=coords[i][0],.y=coords[i][1]};
此外,还应小心使用float
f
声明数组坐标:

{{1f,3f},{5f,7f},{-2f,-3f};

您可能希望使用
distance+=
而不是
distance=
,并将
add\u coords
重命名为
contractive\u distance\u-to\u-coords
,也可以使用
t\u-point
而不是
t\u-coords
// pointer to array of two
float (*this)[2], (*next)[2];

for (int i=0; i < size; i++) {
    this = &coords[i];
    next = &coords[i+1];
    distance += sqrtf(powf((*this)[0] - (*next)[0],2) + powf((*this)[1] - *(next)[1],2));
}