私は 1 日の大半を、連結リストを使った簡単なプログラムを書こうとしてきました。私の主な問題は、私がアクセスしているメモリが私が思っているものではない理由を理解していないようです。私はprintfに夢中で、可能な限りすべての形式のデータを出力していますが、それが機能しない理由を理解するのにまだ苦労しています。
たとえば、&head
を取る関数にを渡し、内部の値(したがって) が であるnode **location
かどうかを確認したい場合、 を使用する必要があるか、 を使用する必要があるか、後者が正しいようですが、なぜですか?location
head
NULL
if(!*location) return;
if(!location) return;
node *current
また、物事を追跡するために関数内に を作成したい場合は、 node* current = *head
orから始めるべきですか?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(¤t, i+1))
{ ++i; }
printf("Pritning...\n");
print_linked_list(&head);
return 0;
}