C编程:使用struct在for循环期间访问数组中的数组

时间:2018-08-21 11:15:39

标签: c arrays pointers for-loop struct

主要是在到达for循环并尝试访问数组中的x和y坐标以计算两者之间的距离时,我很难使此功能完成。

有一个涉及位置的结构,称为locations_t,带有字段

x_loc和y_loc,我的位置数组看起来像

locations[0] = {{0, 0}};

因此程序希望返回以下输出,但这样做是要查找与起始值相距min_dist的locations [i]。

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]

这是我的代码

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;
}

2 个答案:

答案 0 :(得分:2)

如果您像这样locations[i][0],将locations变量视为二维数组,它将无法访问结构的第一个成员。

要访问structure个成员,您可以使用

  

dot(.)运算符用于非指针变量,或者arrow(->)运算符用于   指针变量后跟成员名称。

像下面一样。

  int dist = (query_loc.x_loc - locations[i].x_loc) + (query_loc.y_loc - locations[i].y_loc);

代替

int dist = (query_loc.x_loc - locations[i][0]) + (query_loc.y_loc - locations[i][1]);

答案 1 :(得分:1)

这是一个问题:

int location_nearest (
^^^
Return type int


location_t *nearest 
^^^^^^^^^^^
nearest is a pointer


return nearest;
       ^^^^^^^
       wrong return type