Результат код 1 по-прежнему 10
после освобождения указателя p
и p
не NULL
.
входные данные с кодом 2 равны 5
(длина) и 1 2 3 4 5
для значения каждого узла, но на выходе ничего нет при условии, что все следующие узлы не являются NULL
.
Мой вопрос заключается в том, что, основываясь на логике кода 1 , не должны ли печататься все значения узлов, поскольку они не NULL
?
Может кто-нибудь объяснить мне? Большое вам спасибо!
код 1 :
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p = (int*)malloc(sizeof(int));
*p = 10;
free(p);
if (p != NULL) {
printf("%d\n", *p);
}
return 0;
}
код 2 :
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
struct Node *next;
int value;
} Node, *list;
list create_Node() {
list head = (list)malloc(sizeof(Node));
if (!head)
exit(-1);
list tail = head;
int len;
int val;
printf("Please enter the length of the list:\n ");
scanf("%d", &len);
for (int i = 0; i < len; i++) {
list new = (list)malloc(sizeof(Node));
if (!new)
exit(-1);
printf("Please enter the value of the node:\n ");
scanf(" %d", &val);
new->value = val;
tail->next = new;
tail = new;
}
return head;
}
int delete_List(list l) {
if (l == NULL) {
printf("List is empty!");
exit(-1);
}
list temp;
while (l) {
temp = l->next;
free(l);
l = temp;
}
return 1;
}
int main() {
Node *n = create_Node();
n = n->next;
delete_List(n);
while (n->next != NULL) {
printf("%d\n", n->value);
n = n->next;
}
return 0;
}