开发者

Array of structs in C

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


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
   ...
}


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.


Use malloc():

http://en.wikipedia.org/wiki/Malloc


malloc is your friend here.

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

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


Based on your replies to other answers it looks like you need a dynamic data structure like a linked list. Take a look at the queue(3) set of facilities.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜