tgai
tgai

Reputation: 1115

Creating an array of structs

So I am attempting to modify some code and I need to create an array of a struct. The struct is declared as follows:

typedef struct header
{
    int sample_rate;
    int num_channels;
    int bit_res;
    int num_samples;
    char *data;
} header;

typedef struct header* header_p;

What is the correct way to create and use an array of this struct? I was attempting something along the lines of:

header_p fileHeader;
...
fileHeader = (header_p)malloc(sizeof(header) * (argc-1));

Which seems to work but I am not sure how to access the array correctly.

EDIT: (Some of my question somehow got chopped off) When I try to access the array like so:

fileHeader[0] = function that returns header_p;

I get the following compile error:

incompatible types when assigning to type ‘struct header’ from type ‘header_p’

EDIT: (Figured this out) After following Lundins advice to remove the silly typedef hiding the struct pointer it became much easier to see what was going on. It was then easier to see that Alex was right about the need to dereference my pointer. I am going to accept Alex's answer since technically that was my issue.

Upvotes: 0

Views: 187

Answers (3)

Alex
Alex

Reputation: 10126

Here:

fileHeader[0] = function that returns header_p;

You forgot pointer dereference.

fileHeader[0] = *function_returning_header_p();

Upvotes: 1

Lundin
Lundin

Reputation: 213832

What is the correct way to create and use an array of this struct?

header* fileHeader;

fileHeader = malloc(sizeof(header) * (argc-1));
  • The pointer typedef doesn't make sense and makes your program unreadable.
  • Casting the result of malloc doesn't make sense.
  • You allocated sizeof(header) * the number of arguments and then -1 byte and not -1 argument as intended. Watch operator precedence. This is a bug, you are allocating too much memory.

Upvotes: 2

Kyurem
Kyurem

Reputation: 1869

You can access it like this:

fileHeader[0].bit_res     = ...
fileHeader[1].num_samples = ...

Since it's an pointer, you deference it at an index with the []. Then you access the members with the ..

Upvotes: 0

Related Questions