1

I'm trying to add a struct student to an array. I am trying to do this by allocating some memory to begin with, and then for each additional student using realloc to expand the allocated memory to fit one more. While the first element is added perfectly when I try to add the second the data of the first gets messed up and the second isn't even added correctly.

I have tried removing the realloc function just to see if it would work. I set the size from the beginning to like 5*sizeof(student) and it worked perfectly as I wanted. So I feel like the problem is with my use of the realloc function. Below I have put the addStudent function and the switch case in which it is called.

//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;
}
Mavil
  • 33
  • 5

0 Answers0