I am working on a C program that holds an array of pointer to structs. First the struct looks like this:
typedef struct
{
int ID;
char Name [20];
} rec;
Then I have a function that creates 1 of these structs:
struct rec* addEntry(){
rec *temp;
temp = malloc(sizeof(rec));
printf("Please give me an ID number\n");
scanf("%d", &temp->ID);
printf("Now give me a name, maximum size for this is 20 characters\n");
scanf("%s", &temp->Name);
return temp;
}
Now this function works fine, it creates the struct and returns the pointer towards that struct I then have another function that creates a pointer array and fills it with pointers towards the structs:
struct rec* returnPointerToPointerArray()
{
rec *pointerArray[2];
pointerArray[0] = addEntry();
pointerArray[1] = addEntry();
printf("ID in main : %d\n", pointerArray[0]->ID);
printf("Name in main : %s\n", pointerArray[0]->Name);
printf("ID in main : %d\n", pointerArray[1]->ID);
printf("Name in main : %s\n", pointerArray[1]->Name);
pointerArray = malloc(sizeof(rec*)*2);
return pointerArray;
}
For checking what happens I print the values that are stored at the places in the pointer array. At this point the values in the pointer array are correct.
However now I need to malloc room for this pointerArray and return a pointer to this pointer array, and that is where I get stuck.
The malloc line gives me an error:
error: incompatible types when assigning to type 'struct rec *[(sizetype)(size)]' from type 'void *'
Now to clarify I cannot use a linked list, I have to use an array of pointers instead. To add in my main loop I have another error in the following bit of code:
rec *pointerArray[2];
pointerArray = returnPointerToPointerArray(2);
printf("ID in main : %d\n", pointerArray[0]->ID);
printf("Name in main : %s\n", pointerArray[0]->Name);
This gives me the following error:
error: incompatible types when assigning to type 'struct rec *[2]' from type 'struct rec *'
Any help is more then welcome.
Thanks in advance, Ylva
struct recis not defined anywhere. If you writestruct rec *then that defines a new type, which is incompatible withrec.