我正在调用下面的函数,该函数计算传入变量中给定的值。但是,当函数 (calculate_distance
) 运行时,传递给函数的变量 (loc_ptr
) 中包含的数据似乎发生了变化。
我单步查看代码发现变量loc_ptr
受到函数调用的影响,而不是在函数本身内部。
该函数正在 while 循环中被调用。 while 循环的第一次迭代计算正确,只有在后续迭代中才会出现问题。
_注意:location 是一个类型定义的结构,包含 char *name、双纬度、双经度。 options
是一个 double 组。_
double calculate_distance(location from, location to) {
return to.latitude - from.latitude;
}
main() {
location current_location = {"Plymouth", 50.378565, -4.134339};
location locations[3] = {{"Padstow", 50.5384, -4.9378},
{"Newquay", 50.412, -5.0757},
{"Boscastle", 50.684, -4.6929}};
// create a pointer to an array of locations.
location* loc_ptr;
loc_ptr = &locations[0];
double options[3];
int i = 0;
int position = 3;
while (i < position) {
// calculate the distance between the current and other locations
options[position] = calculate_distance(current_location,
loc_ptr[position]);
position--;
}
// handle the rest of the algorithm
}
注意:该代码是一个更大算法的一部分,它被剪短了,因为它会很长。 while 循环结束后,loc_ptr
数组将被重建以删除其中一个元素。
最佳答案
堆栈损坏?检查选项[]位置[]数组的大小。使用断言来避免越界也很好。
所以,现在我发现索引有问题。 locations[] 数组有 3 个元素,但您在第一个循环期间访问第四个元素 (loc_ptr[position] -> loc_ptr[3]),与 options[] 相同。
关于c - 指针在不应该受到影响的函数调用上受到影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4990178/