Array of Structures in C

I am trying to create an array of structures as well as a pointer to this array. I do not know how large the array is, so it must be dynamic. My structure will look something like this:

typedef struct _stats_t { int hours[24]; int numPostsInHour; int days[7]; int numPostsInDay; int weeks[20]; int numPostsInWeek; int totNumLinesInPosts; int numPostsAnalyzed; } stats_t; 

... and I need to have several such structures for each file (unknown amount), which I will analyze. I am not sure how to do this. I don't like the following approach due to array size limitation:

 # define MAX 10 typedef struct _stats_t { int hours[24]; int numPostsInHour; int days[7]; int numPostsInDay; int weeks[20]; int numPostsInWeek; int totNumLinesInPosts; int numPostsAnalyzed; } stats_t[MAX]; 

So how do I create this array? Also, will the pointer to this array look like this?

 stats_t stats[]; stats_t *statsPtr = &stats[0]; 
+5
c arrays struct
Apr 04 '10 at 21:15
source share
5 answers

Here's how to do it usually:

 int n = <number of elements needed> stats_t *ptr = malloc (n * sizeof (stats_t)); 

Then, to fill it,

 for (int j = 0; j < n; ++j) { ptr [j] .hours = whatever ptr [j] .days = whatever ... } 
+5
Apr 04 '10 at 21:20
source share

The second pointer option is good.

If you want to dynamically highlight things, try:

 stats_t* theStatsPointer = (stats_t*) malloc( MAX * sizeof(stats_t) ); 

as Roland suggests.

Just don't forget

 free(theStatsPointer); 

when you are done.

+2
Apr 04 2018-10-21T00:
source share
0
Apr 04 2018-10-21T00:
source share

malloc is your friend here.

 stats_t stats[] = (stats_t*)malloc(N * sizeof(stats_t)); 

stats sort is a pointer to an array. Or you can use the stats[3] syntax as if it were explicitly declared as an array.

0
Apr 04 2018-10-21T00:
source share

Based on the answers to other answers, it looks like you need a dynamic data structure, such as a linked list. See the queue(3) feature set.

0
Apr 04 '10 at 21:40
source share



All Articles