[英]Head Pointer is changing with linked list items
該程序應該打印新元素和開始元素。 但是每次我分配一個新元素時,開始元素都會發生變化。 init_class()
返回指向類的指針。
/*
Class->Albert
|
V
Einstein
*/
#include "datadef.h"
int main(int argc, char* argv[])
{
char Name[30][30];
if (argc != 2)
{
printf("Incorrect number of arguments, please retry...\n");
exit(0);
}
Class* classp;
classp = init_class();
FILE* fp;
fp = fopen(argv[1],"r");
if (fp == NULL)
{
printf("File pointer allocation error...Ending the program..\n");
exit(0);
}
int count = 0;
Student* prevp;
Student* currp;
while(!feof(fp))
{
fscanf(fp,"%s",Name[count]);
currp = init(Name[count]);
if (!count)
{
classp->startp = currp;
printf("Assigned the head pointer\n");
}
else
{
prevp->nextp = currp;
printf("appending to the pre-existing list\n");
}
count+=1;
prevp = currp;
printf("Current : %s \n",currp->name);
printf("Head : %s \n",classp->startp->name);
printf("\n\n");
}
結果:
指定頭指針
當前:阿爾伯特
負責人:阿爾伯特
追加到先前存在的列表
當前:愛因斯坦
負責人:愛因斯坦
預期結果:
指定頭指針
當前:阿爾伯特
負責人:阿爾伯特
追加到先前存在的列表
當前:愛因斯坦
負責人:阿爾伯特
這是init()
/*init()*/
Student* init(char* name)
{
Student* currentp = (Student*)malloc(sizeof(Student));
if (!currentp)
{
printf("pointer allocation problem..Ending the program...\n");
exit(0);
}
currentp->name = name;
currentp->nextp = NULL;
currentp->scoreHeadp = NULL;
return currentp;
}
您使用的是相同的char Name[30];
為每個學生。
編輯您的初始化函數:
/*init()*/
Student* init(char* name)
{
Student* currentp = (Student*)malloc(sizeof(Student));
/* Allocate memory also for the student name */
currentp->name = (char *)malloc(strlen(name) * sizeof(char));
if (!currentp)
{
printf("pointer allocation problem..Ending the program...\n");
exit(0);
}
//currentp->name = name;
strncpy(currentp->name, name, strlen(name));
currentp->nextp = NULL;
currentp->scoreHeadp = NULL;
return currentp;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.