I'm struggling to create array of structs (with realloc) in function and return the array.
The problem is when I make a breakpoint outside the function its shows me that the array is equal to NULL (and its means that its never created the array right?)
When I'm changing the code and make the array static.. it's working, but when I'm trying to make it dynamic.. the problems begins.
the function that should fill and create the array:
int ReadAllDate (Person *b)
{
int count=0;
char choice;
b = (Person*)malloc(sizeof(Person));
printf("Would you like to enter a person?(y,n)\n");
choice = getchar();
while(choice == 'y')
{
b = (Person*)realloc(b,(count+1) * sizeof(Person));
getchar();
ReadPerson(b+count);
printf("Done!\n");
count++;
getchar();
printf("Would you like to add a person?(y,n)\n");
choice = getchar();
}
printf("The number of entered persons is %d\nBye\n", count);
return count;
}
{first I allocate memory for this array of 1 person (in the malloc) and then for every person the user adding I reallocating the array for more person}
for what I understand, because b is a pointer, everything I do to this pointer in this function should affect it for the whole code.
In here is the main:
int main(int argc, const char * argv[])
{
Person *b;
int count;
int ind1, ind2;
count = ReadAllDate(b);
printf("insert the first index (the smaller): ");
scanf("%d", &ind1);
printf("insert the second index (the bigger): ");
scanf("%d", &ind2);
PrintRange(b, count, ind1, ind2);
}
When I pass b to other function PrintRange to print the structs array, its not printing the elements from this array probably because there is nothing in b. why is that?
I'm reminding again, when I make b static thats means I'm declaring b in the main as
Person b[SIZE];
and in the function ReadAllDate don't trying to allocate its size the code working.
{ please don't tell me to use other function beside the ones I use here because I never learned in my university to use other functions.. so when I will finish the course ill improve my coding skills and use better functions but for now I want to use what the professor teach us :) }