Я все еще изучаю C, и в какой-то момент у меня должны быть неправильно понятые указатели.
У меня сложилось впечатление, что следующие строки будут копировать адрес памяти, хранящийся в l->first
в temp
. Они оба struct list_el*
указатели, поэтому я не вижу проблемы.
struct list_elt * temp;
temp = l->first;
Выполнение моего примера кода дает мне бесконечный цикл:
user@machine:~$ gcc question.c
user@machine:~$ ./a.out | head
append(): l->first->val: 30, l->first->next == NULL: 1
main() : l->first->val: 30, l->first->next == NULL: 1
print() : l->first->val: 30, l->first->next == NULL: 1
print() : temp->val: 30, temp->next == NULL: 0
print() : temp->val: 30, temp->next == NULL: 0
print() : temp->val: 30, temp->next == NULL: 0
print() : temp->val: 30, temp->next == NULL: 0
print() : temp->val: 30, temp->next == NULL: 0
print() : temp->val: 30, temp->next == NULL: 0
print() : temp->val: 30, temp->next == NULL: 0
Вот question.c
. Мне жаль, что я не мог сузить это дальше, каждый раз, когда я делаю, проблема, кажется, волшебным образом исчезает.
#include <stdio.h>
#include <stdlib.h>
struct list_elt {
int val;
struct list_elt * next;
};
struct linked_list {
struct list_elt* first;
};
void print(const struct linked_list * l);
struct linked_list* new_list(void);
void append(struct linked_list* l, int value);
main()
{
struct linked_list * l;
l = new_list();
append(l, 30);
printf("main() : l->first->val: %d, l->first->next == NULL: %d\n", l->first->val, l->first->next == NULL);
print(l);
}
struct linked_list* new_list()
{
struct linked_list* l;
l = (struct linked_list*) malloc(sizeof(struct linked_list));
l->first = NULL;
return l;
}
void append(struct linked_list* l, int value)
{
struct list_elt el = {0, NULL};
el.val = value;
el.next = NULL;
if (l->first == NULL) {
l->first = (struct list_elt*) ⪙
printf("append(): l->first->val: %d, l->first->next == NULL: %d\n", l->first->val, l->first->next == NULL);
} else {
printf("append(): Unimplemented\n");
}
}
void print(const struct linked_list * l)
{
printf("print() : l->first->val: %d, l->first->next == NULL: %d\n", l->first->val, l->first->next == NULL);
struct list_elt * temp;
temp = l->first;
while (temp != NULL) {
printf("print() : temp->val: %d, temp->next == NULL: %d\n", temp->val, temp->next == NULL);
temp = temp->next;
}
printf("\n");
}
Спасибо.