#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
struct node* nc(int data) {
struct node* temp = (struct node*)(malloc(sizeof(struct node)));
temp->data = data;
temp->next = NULL;
return temp;
}
int getcount(struct node* head){
int count = 0;
struct node* temp= head;
while(temp!=NULL){
count++;
temp=temp->next;
}
return count;
}
int getpositionofelement(int data,struct node* head){
int count=0;
while(head->data!=data){
count++;
head=head->next;
}
return count;
}
int main()
{
struct node h;
struct node* head = &h; //(struct node*)malloc(sizeof(struct node));
h.data=5;
struct node* a = nc(19);
struct node* b = nc(25);
struct node* c = nc(12);
h.next = a;
a->next=b;
b->next=c;
free(b);
int count = getcount(head);
printf("the count is %d \n",count);
int l = 5;
printf("the position of %d in linkedlist is %d \n",l,getpositionofelement(l,head));
while(head!=NULL){
printf("%d \n",head->data);
head=head->next;
}
}
当我释放节点b
时,为什么链接列表不会在b
终止?将指针作为参数后,free()
函数如何工作?
答案 0 :(得分:1)
free()从堆中释放内存,这就是全部。您需要将指针设置为null。你的指针可以包含一个存储器的地址,这个地址是免费的:它 这是一个无效的地址,但它仍可存储在您的指针变量中。