C (C89) 当使用 for 循环将结构分配给结构变量时,它们都被设置为第一次迭代结果的值

标签 c struct variable-assignment

我有一个返回位置结构的函数,这是它们分配给一艘船的。我遇到的问题是,当我使用 for 循环遍历船舶时,返回的位置结构是为 for 循环的所有迭代设置的值。

当我打印到终端时,该函数实际上正确计算了值,因此它们实际上具有不同的值。

有人能明白为什么该值保持第一次迭代中返回的值吗?

位置结构有 2 个 double 变量 loc 和 lat。

mday_ptr 是一个带有船舶指针的 Mayday 调用数组

ship 是一艘船*,它有一个位置结构作为成员

代码:

for(i=0; i < mday_size; i++){
    (mday_ptr + i)->ship->loc = calculate_new_ship_loc(
                        (mday_ptr + i)->ship->loc, (mday_ptr + i)->ship->speed,
                        (mday_ptr + i)->ship->course, time_diff);

                printf("updated latitude : %f \t new longitude: %f \n",
                        mday_ptr->ship->loc.lat, mday_ptr-> ship->loc.lng);(mday_ptr + i)->ship->loc = calculate_new_ship_loc(
                        (mday_ptr + i)->ship->loc, (mday_ptr + i)->ship->speed,
                        (mday_ptr + i)->ship->course, time_diff);

                printf("updated latitude : %f \t new longitude: %f \n",
                        mday_ptr->ship->loc.lat, mday_ptr-> ship->loc.lng);
    }
}

返回位置的函数:

location calculate_new_ship_loc(location loc, float spd, float crs,
        float t_diff) {

    printf("start lat : %f \t start lng: %f\n", loc.lat, loc.lng);
    location new_loc;

    double LTF;
    double LGF;

    float course_in_rad;
    float lat_in_rad;

    course_in_rad = crs * M_PI / 180.0;
    lat_in_rad = loc.lat * M_PI / 180.0;

    LTF = (loc.lat) + (spd * cos(course_in_rad) * t_diff) / 3600;

    LGF = (loc.lng) + (spd * sin(course_in_rad) * t_diff /
            cos(lat_in_rad)) / 3600;

    new_loc.lat = LTF;
    new_loc.lng = LGF;

     printf("end lat : %f \t end lng: %f\n", new_loc.lat, new_loc.lng);

    return new_loc;

}

输出:

start lat : 51.750000    start lng: -4.300000
end lat : 51.766603      end lng: -4.297654
updated latitude : 51.766603     new longitude: -4.297654 
start lat : 52.100000    start lng: -6.000000
end lat : 52.100000      end lng: -5.293325
updated latitude : 51.766603     new longitude: -4.297654 
start lat : 52.000000    start lng: -5.900000
end lat : 52.616941      end lng: -5.723307
updated latitude : 51.766603     new longitude: -4.297654 

最佳答案

解决方案非常简单,问题是当我 printitng 时,我总是引用相同的结构。

之前的代码:

 printf("updated latitude : %f \t new longitude: %f \n",
                        mday_ptr->ship->loc.lat, mday_ptr-> ship->loc.lng);

解决方案:

 printf("updated latitude : %f \t new longitude: %f \n",
                        (mday_ptr + i)->ship->loc.lat, (mday_ptr + i)-> ship->loc.lng);

关于C (C89) 当使用 for 循环将结构分配给结构变量时,它们都被设置为第一次迭代结果的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20444449/

相关文章:

php - 在 foreach() 表达式中,值是在键之前还是之后定义的?

c - 用C语言访问Gmail

c - 64 位十六进制的可移植 printf 格式说明符?

c - 使用无缓冲 IO 例程询问和读取用户输入

c++ - 比较C++中的结构

php - 在 PHP 中将单值数组转换为变量的快速方法?

c - AH=2的BIOS INT 13H每次只能读取72个扇区。为什么?

c - 尝试实现我自己的列表时出现内存错误

c - 在c中插入单链表

c# - C#中的对象赋值