我正在学习连锁表并开始编写如下代码:
/*chaintab.h*/
#ifndef __CHAIN_TABLE__
#define __CHAIN_TABLE__
#include<stdio.h>
#include<stdlib.h>
#endif
struct grade{
int score;
struct grade *next;
};
typedef struct grade NODE;
NODE *create_chaintab(){
NODE *head,*tail,*pnode;
int score;
head = (NODE *)malloc(sizeof(NODE));
if(head == NULL){
return NULL;
}
head->next = NULL;
tail = head; /*for there is only 1 node here right now*/
while(1){
printf("What is the score(to quit please enter a negative number)?\n>>>");
scanf("%d",&score);
if(score < 0){
break;
}
pnode = (NODE *)malloc(sizeof(NODE));
if(pnode == NULL){
return NULL;
}
pnode->score=score;
tail->next = pnode;
tail=pnode;
}
return head;
}
void clean_all(NODE *head){
NODE *p,*q;
p = head;
while(p->next != NULL){
q = p->next;
p = p->next->next;
free(q);
}
free(head)
}
/*chaintab.c*/
#include"chaintab.h"
int main(){
NODE *head;
head = create();
if(head==NULL){
printf("***ERROR***:failed to create a chaintab.");
return 1;
}
printf("+++DEBUG+++:\n");
printf("address of head: %p\n",&head);
printf("size of head: %d\n",sizeof(head));
printf("next element size: %d\n",sizeof(head->next));
printf("next element address: %p\n",&head->next);
clean_all(head);
printf("\n***Chain table cleaned***\n");
printf("Address of head and next element: head(%p:%d)->next(%p:%d)\n",&head,sizeof(head),&head->next,sizeof(head->next));
return 0;
}
我找到了head,它的下一个元素在我释放它们之后仍然存在。
这是图片:
你可以看到head的地址及其下一个元素从未改变过。
我有3个问题: