This program is supposed to print new element and the start element. But the start element is getting changed every time I assign a new element. init_class()
returns a pointer to 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");
}
Result:
Assigned the head pointer
Current : Albert
Head : Albert
appending to the pre-existing list
Current : Einstein
Head : Einstein
Expected result:
Assigned the head pointer
Current : Albert
Head : Albert
appending to the pre-existing list
Current : Einstein
Head : Albert
Here's 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;
}
You are using the same char Name[30];
for every student.
Edit your init function:
/*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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.