main.h
#define DATA struct data
DATA
{
int id;
char data;
}
main.c
DATA *listOfData[100];
So at this
I'm not sure why printf
would just freeze, but there's a couple of things wrong with this. First, all the pointers in your DATA*
array are uninitialized. You probably intended to make an array of DATA
, instead of an array of DATA
pointers:
DATA listOfData[100];
You also didn't end the struct with a semicolon, so it seems unlikely that this would even compile:
#define DATA struct data
DATA
{
int id;
char data;
};
Finally, you're using printf
in a rather unsafe way; the first argument needs to be a format string, or you can get weird behavior if the first argument has a %
in it:
printf("%c\n", listOfData[5].data);
You haven't shown any memory allocation for the DATA *. Either declare your array as an array of struct data, like:
DATA listOfData[100];
or allocate memory dynamically and assign the pointers in your array.
This is because you have defined an array of pointers. But you never initialized any of the pointers.
Therefore:
printf(listOfData[5]->data);
will crash (undefined behavior) because you are dereferencing the (invalid) pointer at index 5.
*(And that's a very odd way to define a struct...)
To fix this issue, you will need to allocate for each of the pointers in the array. If you don't actually need it to be an array of pointers, then it might be better to just make it array of the struct itself:
DATA listOfData[100];
and access it as:
listOfData[5].data
Then you don't have to deal with allocating each element.