我只是亂搞鏈表,但似乎我有很多錯誤的東西在我的腦海裏。我已經試過這個功能,我無法得到它的工作。我認爲我可以通過簡化它,但它仍然不起作用。它通常只打印第一個元素,然後是隨機大數(內存地址最有可能)鏈接列表錯誤 - C
我只是想創建一個列表並打印其內容。
#include <stdio.h>
#include <stdlib.h>
struct el{
int value;
struct el *next;
};
typedef struct el Elem;
int main()
{
int nr, i;
struct el *Head, *Conductor;
Head = malloc(sizeof(Elem));
Conductor = Head;
printf("How many elements do you want to add? ");
scanf("%d", &nr);
for(i = 0; i < nr; i++)
{
printf("Enter value for element %d: ", i);
scanf("%d", &(Conductor->value));
Conductor = Conductor->next;
Conductor = malloc(sizeof(Elem));
}
free(Conductor->next);
Conductor->next = NULL;
Conductor = Head;
printf("\n");
for(i = 0; i < nr; i++)
{
printf("%d -> ", Conductor->value);
Conductor = Conductor->next;
}
return 0;
}
首先分配內存,然後分配該值。 – 0xc0de