Reputation: 1115
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
Reputation: 10126
Here:
fileHeader[0] = function that returns header_p;
You forgot pointer dereference.
fileHeader[0] = *function_returning_header_p();
Upvotes: 1
Reputation: 213832
What is the correct way to create and use an array of this struct?
header* fileHeader;
fileHeader = malloc(sizeof(header) * (argc-1));
Upvotes: 2
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