Jeremy Guy
Jeremy Guy

Reputation: 109

Defining an array of structures in C?

main.h

#define  DATA  struct   data
DATA
{
  int id;
  char data;
}

main.c

DATA *listOfData[100];

So at this point I will/should be able to access DATA in the list like this:

printf(listOfData[5]->data);

It isn't letting me do it, the run just freezes on that last print f...no error or anything.

Upvotes: 2

Views: 263

Answers (3)

Michael Mrozek
Michael Mrozek

Reputation: 175365

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);

Upvotes: 1

thiton
thiton

Reputation: 36049

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.

Upvotes: 0

Mysticial
Mysticial

Reputation: 471229

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.

Upvotes: 2

Related Questions