在C结构数组 [英] Array of structs in C

查看:116
本文介绍了在C结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建结构的数组,也是一个指针数组。我不知道该数组多大将是,所以它应该是动态的。我将结构看起来是这样的:

  typedef结构_stats_t
{
 INT小时[24]; INT numPostsInHour;
 INT天[7]; INT numPostsInDay;
 INT周[20]; INT numPostsInWeek;
 INT totNumLinesInPosts;
 INT numPostsAnalyzed;} stats_t;

...我需要有这些结构的每个文件(金额不详),我将分析的多。我不知道如何做到这一点。我不喜欢因为数组的大小限以下办法:

 #定义MAX 10
typedef结构_stats_t
{
 INT小时[24]; INT numPostsInHour;
 INT天[7]; INT numPostsInDay;
 INT周[20]; INT numPostsInWeek;
 INT totNumLinesInPosts;
 INT numPostsAnalyzed;} stats_t [MAX];

所以,我将如何创建这个数组?此外,将一个指向该数组将如下呢?

  stats_t统计[];
stats_t * statsPtr =安培;统计[0];


解决方案

这是它是如何做的,通常:

  INT N =<需要的元素&GT的数量;
stats_t * PTR =的malloc(N * sizeof的(stats_t));

然后,以填充它,

 为(INT J = 0; J< N ++ j)条
{
   PTR [J] .hours =什么
   PTR [J] .days =什么
   ...
}

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:

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

Then, to fill it in,

for (int j = 0;  j < n;  ++j)
{
   ptr [j] .hours = whatever
   ptr [j] .days = whatever
   ...
}

这篇关于在C结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆