전달 된 변수에 주어진 값을 계산하는 아래 함수를 호출하고 있습니다. 그러나 함수 (calculate_distance
)가 실행되면 함수에 전달 된 변수 (loc_ptr
)에 포함 된 데이터가 변경된 것처럼 보입니다.포인터가 함수 호출에 영향을받는 곳 :
코드를 통해 변수 loc_ptr
이 함수 자체가 아니라 함수 호출에 영향을 받는다는 것을 알게되었습니다.
함수가 while 루프에서 호출되고 있습니다. while 루프의 첫 번째 반복은 올바르게 계산됩니다. 문제가 발생하는 것만 후속 반복에서 발생합니다.
_ 주 : location은 char * name, double latitude, double longitude가 포함 된 typedef'ed 구조체입니다. options
는 doubles._
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
배열이 다시 구성되어 요소 중 하나가 제거됩니다.
무엇이'위치'입니까? 어떻게 정의/할당됩니까? – jswolf19
옵션 []이 정의 된 방법 및 위치는 무엇입니까? – pmod
latitude 대 lattiude? –