Note that there are some explanatory texts on larger screens.

plurals
  1. POPointer is Affected on Function Call Where it Shouldn't Be
    primarykey
    data
    text
    <p>I am calling the function below, which calculates a value given in the passed in variables. However, when the function (<code>calculate_distance</code>) runs, the data contained in the variable (<code>loc_ptr</code>) that is passed into the function seems to change.</p> <p>I have stepped through the code to find that the variable <code>loc_ptr</code> is affected on the function call, rather than inside the function itself.</p> <p>The function is being called in a while loop. The first iteration of the while loop calculates correctly, it is only on subsequent iterations that the problem seems to occur.</p> <p>_Note: location is a typedef'ed struct containing char *name, double latitude, double longitude. <code>options</code> is an array of doubles._</p> <pre><code>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 = &amp;locations[0]; double options[3]; int i = 0; int position = 3; while (i &lt; 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 } </code></pre> <p><em>Note: The code is part of a larger algorithm, it's cut short as it would be quite long. After the while loop finishes, the <code>loc_ptr</code> array is rebuilt to remove one of the elements.</em></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload