Reputation: 113
I am having trouble making this function complete, mainly once i get to the for loop and try to access the x and y coordinate within the array to calculate the distance between the two.
there is a structure involved called locations_t with fields
x_loc and y_loc and my locations array looks like
locations[0] = {{0, 0}};
so the program looks to return the following output but does so to find the the locations[i] that is the min_dist from the starting value.
query_loc = 10, 7
locations[0] = {{10, 10}} //distance between the two is 3
query_loc = 10, 7
locations[1] = {{9, 7}} // distance between is 1
// nearest would return locations[1]
this is my code
int location_nearest (location_t query_loc, location_t locations[], int num_locations)
{
// (Task 5.1) If num_locations equal to or less than 0, return NULL.
if(num_locations <= 0)
{
return NULL;
}
// (Task 5.2) Declare and initialise a pointer to location_t called nearest.
// The initial value is the address of the first element in the array.
location_t *nearest = &locations[0];
// (Task 5.3) Declare and initialise an integer called min_dist.
// The initial value is the city block distance from the query to
// the first element of the array.
// Hint: use location_dist.
int min_dist = location_dist(query_loc, locations[0]);
// (Task 5.4) Set up a for loop to iterate over the array.
// Skip the first element of the array, because we already know
// the distance from the first element to the query.
for(int i = 1; i < num_locations; i++)
{
// (Task 5.4.1) Compute the city block distance from the query
// to the current element of the array. This is the current
// distance. Make sure you remember it somehow.
int dist = (query_loc.x_loc - locations[i][0]) + (query_loc.y_loc - locations[i][1]);
// (Task 5.4.2) If the current distance is less than min_dist:
if(dist < min_dist)
{
// (Task 5.4.3) Overwrite min_dist with the current distance.
// Overwrite nearest with the address of the current element of
// the array.
min_dist = dist;
nearest = &locations[i]
}
}
// (Task 5.5) Return nearest.
return nearest;
}
Upvotes: 1
Views: 199
Reputation: 12732
If you do locations[i][0]
like this you are treating locations
variable as two dimensional array and it will not access the first member of structure.
In order to access structure
members you can use,
dot(.)
operator for non pointer variable orarrow(->)
operator for pointer variable followed by member name.
Like below.
int dist = (query_loc.x_loc - locations[i].x_loc) + (query_loc.y_loc - locations[i].y_loc);
Instead of
int dist = (query_loc.x_loc - locations[i][0]) + (query_loc.y_loc - locations[i][1]);
Upvotes: 2
Reputation: 44310
Here is one problem:
int location_nearest (
^^^
Return type int
location_t *nearest
^^^^^^^^^^^
nearest is a pointer
return nearest;
^^^^^^^
wrong return type
Upvotes: 1