I'm trying to create a function for adding 1 element to each of the three pointer arrays (firstArray, lastArray, scoreArray). For this particular assignment, I'm supposed to use pointers and dynamic memory but no structures.
As the program is now, it automatically moves to adding an additional record and waits for all 3 parts of the user input. However, when the program calls the printRecords() function after running the addRecords() function, I get a segmentation fault. I assume this means I'm not passing the changes made in the addRecords() function back to the main therefore, there is nothing stored where the printRecords() function is trying to read. I've tried several times but have gotten nowhere.
How should I alter the 3 problem lines in addRecords() to pass the changes made to the arrays back to the main?
void printRecords(char **firstArray, char **lastArray, float **scoreArray, int n);
void addRecords(char **firstArray, char **lastArray, float **scoreArray, int *j);
int main(int argc, char** argv) {
int i = 0, n = 0;
printf("Please indicate the number of student records to be entered:");
scanf("%d",&n);
char **firstArray;
char **lastArray;
float **scoreArray;
firstArray = (char **)malloc(n*sizeof(char *));
lastArray = (char **)malloc(n*sizeof(char *));
scoreArray = (float **)malloc(n*sizeof(float *));
for(i=0;i<n;i++)
{
printf("Enter Record %d:",i+1);
firstArray[i] = (char *)malloc(n*sizeof(char));
lastArray[i] = (char *)malloc(n*sizeof(char));
scoreArray[i] = (float *)malloc(n*sizeof(float));
scanf("%s",firstArray[i]);
scanf("%s",lastArray[i]);
scanf("%f",scoreArray[i]);
}
addRecords(firstArray,lastArray,scoreArray,&n);
printRecords(firstArray,lastArray,scoreArray,n);
return (EXIT_SUCCESS);
}
void printRecords(char **firstArray, char **lastArray, float **scoreArray, int n)
{
int i = 0;
printf("\nPrinting %d student records....\n",n);
for(i=0;i<n;i++)
{
printf("Record %d: %s - %s - %.2f\n",i+1,firstArray[i],lastArray[i],*scoreArray[i]);
}
}
void addRecords(char **firstArray, char **lastArray, float **scoreArray, int *j)
{
int t = *j; //Assigning current number of records to temp variable
t++; //Increment by 1
*j = t; //Passes the new number of records back to main
printf("Enter Record %d:",t);
firstArray[t] = (char *)malloc(t*sizeof(char));
lastArray[t] = (char *)malloc(t*sizeof(char));
scoreArray[t] = (float *)malloc(t*sizeof(float));
scanf("%s",firstArray[t]); **//PROBLEM LINES**
scanf("%s",lastArray[t]); **//PROBLEM LINES**
scanf("%f",scoreArray[t]); **//PROBLEM LINES**
printf("\nNew record added successfully");
return;
}