|
こちらのサイトの自己構造体をコンパイルしてみましたが、
最後に入力したものが表示されません。
なぜでしょうか?
リスト表示の関数部分に下記を追加すると最後に入力したリストは表示されますが、このプリント文は表示されません。
printf("p%d\n", p);
検索してもヒットせず分かりませんでしたのでよろしくお願いします。
環境はWin98です。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct list {
int key; /* キー */
char name[20]; /* 名前 */
struct list *next; /* 次のデータへのポインタ */
};
struct list *add_list(int key, char *name, struct list *head);
void show_list(struct list *p);
void free_list(struct list *p);
int main(void)
{
struct list *head; /* 先頭ポインタ */
char name[20];
int key = 0;
head = NULL; /* 先頭ポインタにNULLを設定 */
printf("キーと名前(MAX:19文字)を入力(終了:CTRL+Z)\n");
while (scanf("%d %s", &key, name) != EOF) {
/* リストにデータを登録 */
head = add_list(key, name, head);
}
printf("リストの表示%d",head);
/* リストの表示 */
show_list(head);
printf("リストの開放%d",head);
/* リストの開放 */
free_list(head);
return 0;
}
/*** リストにデータを登録 ***/
struct list *add_list(int key, char *name, struct list *head)
{
struct list *p;
/* 記憶領域の確保 */
if ((p = (struct list *) malloc(sizeof(struct list))) == NULL) {
printf("malloc error\n");
exit(1);
}
/* リストにデータを登録 */
printf("head%d\n", head);
p->key = key;
printf("add_list_key%d\n",p->key);
strcpy(p->name, name);
printf("add_list_name%s\n",p->name);
/* ポインタのつなぎ換え */
p->next = head; /* 今までの先頭ポインタを次ポインタに */
printf("add_list_p->next%d\n",p->next);
head = p; /* 新たな領域を先頭ポインタに */
printf("add_list_head%d\n",head);
return head;
}
/*** リストの表示 ***/
void show_list(struct list *p)
{
while (p != NULL) { /* 次ポインタがNULLまで処理 */
//printf("p%d\n", p);
printf("%3d %s\n", p->key, p->name);
p = p->next;
}
}
/*** リストの開放 ***/
void free_list(struct list *p)
{
struct list *p2;
while (p != NULL) { /* 次ポインタがNULLまで処理 */
p2 = p->next;
printf("p2=%d\t",p2);
printf("free p=%d\t",p);
free(p);
p = p2;
printf("p=%d\t",p);
}
}
|