0

该程序应该打印新元素和开始元素。但是每次我分配一个新元素时,开始元素都会发生变化。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;

}

4

2 回答 2

1

char Name[30];您对每个学生都使用相同的方法。

于 2012-08-10T02:10:05.897 回答
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;
}
于 2012-08-10T03:48:26.140 回答