C中将元素添加到数组的函数在多次运行时给出了意外的代码

时间:2019-06-11 02:05:32

标签: c realloc

我正在尝试将结构学生添加到数组中。我正在尝试通过分配一些内存开始,然后为每个使用realloc的其他学生扩展分配的内存以容纳更多的内存。当我尝试添加第二个元素时,第一个元素被完美地添加了,但第一个元素的数据却被弄乱了,而第二个元素甚至都没有正确添加。

我尝试删除realloc函数只是为了查看它是否有效。我从一开始就将大小设置为5 * sizeof(student),并且按我的要求完美地工作了。所以我觉得问题出在我对realloc函数的使用上。 我在下面放置了addStudent函数和调用它的开关盒。

//The struct student

typedef struct
{
     int id;
     char name[64];
}student;

//the addStudent function that is called in the main

int addStudent(student st,student *stArray)
{
    stArray = realloc(stArray, (arraysize+1)*sizeof(student));
    printf("arraysize = %d",arraysize);
    stArray[arraysize] = createStudent(st.id,st.name);
    printf("\n");
    arraysize++;
    return 0;
}

//switch case in which above function is called. This is somewhere in the main function which 
//is just a menu.

 printf("Enter student id: ");
 scanf("%d",&tempid);
 printf("\nEnter student name: ");
 scanf("%s", tempname);
 printf("\n");
 sttemp = createStudent(tempid,tempname);
 addStudent(sttemp, stArray);
 print(stArray[arraysize-1]);
 break;

//the function called to create the students

student createStudent(int id, char* name)
{
    student st;
    st.id = id;
    strcpy(st.name,name);
    return st;
}

0 个答案:

没有答案