[英]error when trying to run linked list c program
我是編程新手,所以這里的問題是,當我想執行以下程序時,但這僅表明該程序已停止工作。我不知道代碼有什么問題,因為沒有編譯錯誤。任何幫助將不勝感激。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ppl
{
char name[30];
struct ppl *next;
};
main()
{
struct ppl *student1, *student2, *student3, *student4, *temp, *ptr, *x;
struct ppl *head = NULL;
int no;
head = (struct ppl *)malloc(sizeof(struct ppl));
student1 = (struct ppl *)malloc(sizeof(struct ppl));
student2 = (struct ppl *)malloc(sizeof(struct ppl));
student3 = (struct ppl *)malloc(sizeof(struct ppl));
student4 = (struct ppl *)malloc(sizeof(struct ppl));
head->next = student1;
strcpy(student1->name, "Aizar");
student1->next = student2;
strcpy(student2->name, "Chandi");
student2->next = student3;
strcpy(student3->name, "Faizul");
student3->next = student4;
strcpy(student4->name, "Joshua");
student4->next = NULL;
ptr = head;
while (ptr->next != NULL)
{
ptr = (struct ppl *)malloc(sizeof(struct ppl));
ptr = ptr->next;
printf("Name list : %s \n", ptr);
};
return 0;
}
問題出在while循環內。 嘗試這個:
while(ptr->next != NULL)
{
ptr = ptr->next;
printf("Name list : %s \n", ptr );
};
PS: ptr
不需要單獨的內存分配。 它將指向由分配給它的指針所指向的內存位置(在while
循環中)。
注意 : don't give me fish teach me how to fish
一些評論:
ptr = head; // here ptr has the value of head
while (ptr->next != NULL)
{
ptr = (struct ppl *)malloc(sizeof(struct ppl)); // ptr loses the value of head and takes new value given by malloc
ptr = ptr->next; // ptr -> next is null so ptr becomes null
printf("Name list : %s \n", ptr); // generally if you want to print pointers use %p not %s
};
一些跡象:
現在輪到您根據需要更正代碼了。
快樂編碼:D
我認為您的意思是:。)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ppl
{
char name[30];
struct ppl *next;
};
int main( void )
{
struct ppl *student1, *student2, *student3, *student4, *temp;
struct ppl *head = NULL;
student1 = (struct ppl *)malloc( sizeof( struct ppl ) );
student2 = (struct ppl *)malloc( sizeof( struct ppl ) );
student3 = (struct ppl *)malloc( sizeof( struct ppl ) );
student4 = (struct ppl *)malloc( sizeof( struct ppl ) );
strcpy( student1->name, "Aizar" );
student1->next = student2;
strcpy( student2->name, "Chandi" );
student2->next = student3;
strcpy( student3->name, "Faizul" );
student3->next = student4;
strcpy( student4->name, "Joshua" );
student4->next = NULL;
head = student1;
for ( temp = head; temp != NULL; temp = temp->next )
{
printf( "Student Name: %s \n", temp->name );
}
while ( head )
{
temp = head;
head = head->next;
free( temp );
}
return 0;
}
程序輸出為
Student Name: Aizar
Student Name: Chandi
Student Name: Faizul
Student Name: Joshua
至於你的代碼,那么這個循環
while (ptr->next != NULL)
{
ptr = (struct ppl *)malloc(sizeof(struct ppl));
ptr = ptr->next;
printf("Name list : %s \n", ptr);
};
沒有道理。
另外,您無需為磁頭分配單獨的節點。 頭應該是指向第一個分配的“學生”的指針。
考慮到C函數主要應具有返回類型int
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.