簡體   English   中英

C編程:使用struct在for循環期間訪問數組中的數組

[英]C Programming: Using struct Accessing an array within an array during a for loop

我無法完成這個功能,主要是一旦我到達for循環並嘗試訪問數組中的x和y坐標來計算兩者之間的距離。

有一個名為locations_t的結構包含字段

x_loc和y_loc以及我的locations數組看起來像

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

所以程序看起來返回以下輸出但是這樣做是為了找到起始值為min_dist的位置[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;
}

如果你像這樣做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]); 

這是一個問題:

int location_nearest (
^^^
Return type int


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


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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM