0

私は 1 日の大半を、連結リストを使った簡単なプログラムを書こうとしてきました。私の主な問題は、私がアクセスしているメモリが私が思っているものではない理由を理解していないようです。私はprintfに夢中で、可能な限りすべての形式のデータを出力していますが、それが機能しない理由を理解するのにまだ苦労しています。

たとえば、&headを取る関数にを渡し、内部の値(したがって) が であるnode **locationかどうかを確認したい場合、 を使用する必要があるか、 を使用する必要があるか、後者が正しいようですが、なぜですか?locationheadNULLif(!*location) return;if(!location) return;

node *currentまた、物事を追跡するために関数内に を作成したい場合は、 node* current = *headorから始めるべきですか?node* current = headそして、最も重要なのはなぜですか? 後者の方が良いことに気づきましたが、まだ意味がわかりません。ステートメントを型キャストすると警告は消えますが、何も修正されないようです。

ここに私が書いているいくつかの関数があります。コードのどこが意味を成していないかについてのヒントを教えてください。できれば、出力がメモリの場所のように見えて、不良メモリにアクセスしている理由を理解したいと思っています。

#include <stdio.h>
#include <stdlib.h>

typedef struct node_struct
{
    int val;
    struct node *next;
} node;

node* return_create_neck(node **head, int value)
{
    node* ptr;
    *head = ptr = (node *)malloc(sizeof(node));
    (*head)->val = value;
    (*head)->next = NULL;
    return ptr;
}

node* return_append_tail(node **location, int value)
{
    node* ptr;
    *location = ptr = (node *)malloc(sizeof(node));
    (*location)->val = value;
    (*location)->next = NULL;
    return ptr;
}

void print_linked_list(node **head)
{
    if(!head)
        return;

    node *current = head;
    while(current)
    {
        printf("%d ", current->val);
        current = current->next;
    }
    printf("\n");
    return;
}

int main(void)
{
    node *head=NULL, *current=NULL;
    int i=0;
    for( current = return_create_neck(&head, 1);
        i < 4;
        current = return_append_tail(&current, i+1))
    { ++i; }

    printf("Pritning...\n");
    print_linked_list(&head);
    return 0;
}
4

1 に答える 1

2

あなたのreturn_append_tail関数は、あなたがしていない正しい で呼び出されない限り、実際には何も追加しlocationません。

&current->next関数から呼び出す必要がありmainます。

于 2013-06-02T10:12:36.723 に答える