Reputation: 964
struct GENERATIONS
{
char generation[MAX_ROWS][MAX_COLS];
int hasCycle;
};
typedef struct GENERATIONS Generation;
I have an array of type struct:
Generation generations[MAX_GENERATIONS];
I declare a Generation
variable like this:
Generation *currentGeneration = NULL;
currentGeneration = (Generation *) malloc(sizeof(Generation));
and attempt to add a generation to an array of generations: numGenerations is set to 0 then incremented via a loop.
copyGeneration(currentGeneration);
generations[numGenerations] = currentGeneration;
Yet each time, I get the error incompatible types when assigning to type 'Generation' from type 'struct Generation *. I understand this has to do with pointers which I do not understand but need.
Why is it that when I declare the array as:
Generation *generations[MAX_GENERATIONS];
Everything suddenly works?
Upvotes: 1
Views: 124
Reputation: 2625
To solve this problem, you can proceed in a different way. What you can do is this
#define MAX_GENERATIONS 1024 // you can take some other value too
#include <stdio.h>
#include <stdlib.h>
static int count = 0
Generation** push(Generation** generations, Generation obj){
count++;
if (count == MAX_GENERATIONS){
printf("Maximum limit reached\n");
return generations;
if ( count == 1 )
generations = (Generation**)malloc(sizeof(Generation*) * count);
else
generations = (Generation**)realloc(generations, sizeof(Generation*) * count);
generations[count - 1] = (Generation*)malloc(sizeof(Generation));
generations[count - 1] = obj;
return generations;
}
int main(){
Generation** generations = NULL;
Generation currentGeneration;
// Scan the the elements into currentGeneration
generations = push(generations, currentGeneration); // You can use it in a loop
}
Upvotes: 1
Reputation: 141927
currentGeneration
is a Generation *
, not a Generation
.
You need an array of Generation *
to hold it, not an array of Generation
.
Upvotes: 0
Reputation: 51977
Each currentGeneration
is a pointer to a Generation
. Yet when you declare an array Generation generations[MAX_GENERATIONS]
it expects each index to be a Generation
, not a pointer to one. But when you declare the array as Generation *generations[MAX_GENERATIONS]
it expects each index to be a pointer to a Generation
, which is what you are assigning to each index.
Upvotes: 2
Reputation: 987
The error is telling you exactly what's wrong. Your variable currentGeneration
is of type "pointer to Generation", and your variable generations
is of type "array of Generation". You can't assign a pointer to Generation to an index of an array of Generation--you can only assign a Generation.
When you declare the array as Generation *generations[MAX_GENERATIONS]
, everything works because you're assigning a pointer to Generation to an index of an array of pointers to Generation.
Upvotes: 1