简体   繁体   English

头指针随链接列表项而变化

[英]Head Pointer is changing with linked list items

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. 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");
    }

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()

/*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]; 您使用的是相同的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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM