I have a struct which holds 3 char pointers (arbitrary length strings) and I created a dynamic array with malloc since It can have an arbitrary amount of entries. This is my struct data type:
typedef struct student{
char* name;
char* phoneNumber;
char* department;
}STUDENT;
I used a function to realloc to increase the size of the struct array whenever a new entry is needed and another function to print the whole array.
The problem that i encounter is that: I am able to print the new entry inside the addNumber function but it is not always the case when I tried printing outside the addNumber function. Sometimes it works, most of the time I got a segmentation fault: 11 and one time while adding a new entry I got a 'malloc: *** error for object 0x7fc426c058f0: pointer being realloc'd was not allocated'
Here is inside of my main:
int nEntry = 0;
STUDENT* directory = malloc(nEntry * sizeof *directory);
if(directory == NULL){
puts("Unable to allocate memory");
exit(-1);
}
while(1){
int choice = 0;
scanf("%d", &choice);
while(getchar() != '\n');
switch(choice){
case 1:
printDirectory(directory, nEntry);
break;
case 2:
addNumber(directory, &nEntry);
break;
default:
printf("Unknown option!\n");
break;
}
}
return 0;
Here is my addNumber function:
void addNumber(STUDENT* Array, int* nArray){
*nArray += 1;
int x = *nArray - 1;
STUDENT* tempDirectory = realloc(Array, *nArray * sizeof *Array);
if(tempDirectory == NULL){
puts("Unable to allocate memory");
exit(-1);
}
else{
Array = tempDirectory;
Array[x].name = (char*)malloc(sizeof(char*));
Array[x].phoneNumber = (char*)malloc(sizeof(char*));
Array[x].department = (char*)malloc(sizeof(char*));
printf("Name: ");
scanf("%[^\n]", Array[x].name);
while(getchar() != '\n');
printf("Number: ");
scanf("%[^\n]", Array[x].phoneNumber);
while(getchar() != '\n');
printf("Department: ");
scanf("%[^\n]", Array[x].department);
while(getchar() != '\n');
for(int i = 0; i < *nArray; i++){
printf("%s\t%s\t(%s)\n", (Array + i)->name, (Array + i)->phoneNumber, (Array + i)->department);
}
}
}
and Here is my print function:
void printDirectory(STUDENT* Array, int nArray){
int i;
for(i = 0; i < nArray; i++){
printf("%s\t%s\t(%s)\n", (Array + i)->name, (Array + i)->phoneNumber, (Array + i)->department);
}
}
The print function works fine if I hardcode the entry into main, the problem seems to be that whats created in the addNumber function isn't properly passed back? But then for all the arguments i am passing by reference, I am confused why I'm getting an undefined behaviour.