Reputation: 344
typedef struct
{
char*title;
int year;
int length; //in minutes
} record;
record list[1024];
int j;
for(j=0;j<1024;++j)
list[j]=NULL;
I am trying to initialize an array of struct and let each element point to null initially. gcc gives me an error "incompatible types when assigning to type 'record' from type 'void*". How could I solve it? The purpose of doing this is when I access an element I am able to see if it has data or just empty.
Upvotes: 2
Views: 30841
Reputation: 707
If you want to do it one at a time in a for loop, it would look like this
for(j=0;j<1024;++j)
list[j]=(record){0,0,0};
I would suggest using memset(list,0,1024*sizeof(record))
or bzero(list, 1024*sizeof(record))
If you want to do it with pointers, then you could declare your array like this:
record * list[1024];
Then you could set each one to NULL
like you are and malloc each one when you're ready for it.
Upvotes: 3
Reputation: 11609
list[1024];
is array of object of your struct, which you access like
list[j].title;
list[j].year;
list[j].length;
What you are doing is:
list[j]=NULL
list[j]
is of type record
, NULL is void*
. I guess this is not what you have in mind.
Either initialize individual elements in the struct by accessing them individually or use memset
as suggested by others.
Upvotes: 3
Reputation: 12749
Your array is not an array of pointers to record
s, it is an array of record
values. You cannot set the elements of the array to NULL
because they are not pointers. This is not java...
Upvotes: 2
Reputation: 145829
You can initialize your array at declaration time this way:
record list[1024] = {{0}};
Upvotes: 7