头指针正在改变链表项

时间:2012-08-10 01:55:25

标签: c

该程序应该打印新元素和start元素。但是每次分配新元素时,start元素都会发生变化。 init_class()返回指向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");
    }

结果:

  

指定头指针

     

Current:Albert

     

负责人:艾伯特

     

附加到预先存在的列表

     

目前:爱因斯坦

     

负责人:爱因斯坦

预期结果:

  

指定头指针

     

Current:Albert

     

负责人:艾伯特

     

附加到预先存在的列表

     

目前:爱因斯坦

     

负责人:艾伯特

这是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;

}

2 个答案:

答案 0 :(得分:1)

您为每位学生使用相同的char Name[30];

答案 1 :(得分:0)

编辑初始化函数:

/*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;
}