0

次の二重にリンクされたリスト構造があります。

struct coords
{
    int x;
    int y;
    struct coords* previous;
    struct coords* next;
};

ここでは (x, y) として示されている、次の値を持つリンクされたリストがあります。

head                                                          tail
(-1, -1) <--> (0, 1) <--> (2, 1) <--> (1, 0) <--> (0, 2) <--> (-1, -1)

私の実装では、head と tail は常に (-1, -1) です。次の要素を持つサイズ 4 の coords* の配列である newCoords もあります。

[(0, 2), (2, 2), (1, 3), no value]

newCoords には、0 ~ 4 個の要素を割り当てることができます。また、newCoords と呼ばれる int でノードの数を追跡します (現在の値は 3 です)。これらのノードをリンク リストに、テール ノードと最後の非テール ノードの間に追加したいと考えています。このために、次のコードがあります (わかりやすくするために print ステートメントは削除されています)。

void insert (struct coords* position, struct coords* newCoord)
    {
        newCoord->next = position->next;
        newCoord->previous = position;
        position->next = newCoord;
    }
... //here I create the initial linked list
struct coords* newCoords[4]; //4 is the maximum number of new coords that can be added
int numberOfNewCoords = 0;
... //here I fill newCoords, and as I do I increment numberOfNewCoords by 1
if (numberOfNewCoords > 0) //numberOfNewCoords stores the number of coords in newCoords
    {
        struct coords* temp = tail->previous;
        /* add new possible locations to list */
        for (int i = 0; i < numberOfNewCoords; i++)
            {
                insert(temp, newCoords[i]);
                temp = temp->next;
            }
     }

newCoords の最初の 2 つの値は、期待どおりに追加されます。ただし、最後の値はリンク リストに挿入されません。あるべき場所に挿入されるのは、プログラムを実行するたびに変化する番号を持つノードです。リストは

head                                                                                              tail
(-1, -1) <--> (0, 1) <--> (2, 1) <--> (1, 0) <--> (0, 2) <--> (0, 2) <--> (2, 2) <--> (1, 3) <--> (-1, -1)

しかし、代わりに

head                                                                                                          tail
(-1, -1) <--> (0, 1) <--> (2, 1) <--> (1, 0) <--> (0, 2) <--> (0, 2) <--> (2, 2) <--> (9765060, 9770824) <--> (-1, -1)
4

2 に答える 2

0

追加したい新しい座標にメモリを割り当てるのに失敗したと思います。新しい要素を既存のリストに追加するときは、新しい要素のためのスペースを提供するために、事前にメモリが割り当てられていることを確認する必要があります。あなたが投稿したコードは、この部分で修正が必要です-

    for (int i = 0; i < numberOfNewCoords; i++)
                {
                    insert(temp, newCoords[i]);
                    temp = temp->next;
                }

変更後-

    for (int i = 0; i < numberOfNewCoords; i++)
                {
                    temp = malloc(sizeof(struct* coords));
                    insert(temp, newCoords[i]);
                    temp = temp->next;
                }

コンパイラが (struct *) による自動型キャストをサポートしていない場合は、malloc を型キャストできます。

これがうまくいくことを願っています。

于 2013-06-20T07:55:07.027 に答える
0

明確にするために、malloc を使用してメモリを割り当てましたか?

于 2013-06-20T07:10:18.537 に答える