Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of structs in C

Tags:

arrays

c

struct

I'm trying to create an array of structs and also a pointer to that array. I don't know how large the array is going to be, so it should be dynamic. My struct would 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 multiple of these structs for each file (unknown amount) that I will analyze. I'm not sure how to do this. I don't like the following approach because of the limit of the size of the array:

# 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 would I create this array? Also, would a pointer to this array would look something this?

stats_t stats[];
stats_t *statsPtr = &stats[0];
like image 835
Hristo Avatar asked Apr 04 '10 21:04

Hristo


People also ask

Can you put arrays in structs?

A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure. An array within a structure is a member of the structure and can be accessed just as we access other elements of the structure.

What is array of structure explain with example?

The most common use of structure in C programming is an array of structures. To declare an array of structure, first the structure must be defined and then an array variable of that type should be defined. For Example − struct book b[10]; //10 elements in an array of structures of type 'book'

How do you access an array in a struct?

Array elements are accessed using the Subscript variable, Similarly Structure members are accessed using dot [.] operator. Structure written inside another structure is called as nesting of two structures. Nested Structures are allowed in C Programming Language.


2 Answers

This is how it is usually done:

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

Then, to fill it in,

for (size_t j = 0;  j < n;  ++j)
{
   ptr [j] .hours = whatever
   ptr [j] .days = whatever
   ...
}
like image 117
wallyk Avatar answered Sep 23 '22 22:09

wallyk


The second option of a pointer is good.

If you want to allocate things dynamically, then try:

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

as Roland suggests.

Just don't forget to

free(theStatsPointer);

when you're done.

like image 2
Peter K. Avatar answered Sep 24 '22 22:09

Peter K.