嵌套结构的动态数组成员

时间:2014-02-03 09:19:40

标签: c structure dynamic-arrays

我的结构包含一组其他结构:

 typedef struct{
    int cell_Type;      //user association: 0--> Macro 1--> Femto
    int cell_ID;        //cell ID that the user is associated with
}association;

 //User struct
 typedef struct{
    coord c;                //coordinates
    association id;             //association parameters
    capacity cap;               //capacity parameters   
 }usu;

 //Struct with a vector of users
 typedef struct{
     usu user[NUM_USERS+NUM_HS]; //each user is defined by the association (id), etc...
 }vectusers;

void main(int argc,char *argv[])
{
       //.....

       //memory allocation for the structures
       users_ptr=calloc(1,sizeof(vectusers)); //users pointer

       //.....
}

到目前为止一直很好,到目前为止,在程序即将完成之前,需要一个我不知道其大小的数组。

因此,结构将是:

 typedef struct{
    int cell_Type;      //user association: 0--> Macro 1--> Femto
    int cell_ID;        //cell ID that the user is associated with
    int assigned_RBs;   //counter of how many resources have been assigned
    int *RB_number;     //array with size according to assigned_RBs counter
}association;

我的问题在于malloc()和realloc()。实际上我认为我正在使用malloc保留正确的记忆:

users_ptr->user[u].id.RB_number = malloc(1*sizeof(int));

但是当谈到realloc()时,我不会改变数组的大小:

users_ptr->user[index_max_W].id.assigned_RBs++;

size = users_ptr->user[index_max_W].id.assigned_RBs;

users_ptr->user[index_max_W].id.RB_number = realloc((users_ptr->user[index_max_W].id.RB_number),size);

其中index_max_w是具有统计值的最大值的用户的索引。 size和index_max_W都已声明为int。

在这种情况下,有人可以帮我解决问题吗?

1 个答案:

答案 0 :(得分:1)

realloc()的size参数以字节为单位,就像malloc()的参数一样。您的代码似乎省略了realloc()的缩放,如果您访问内存,这将导致(严重)欠分配,从而导致未定义的行为。

应该是这样的:

const size_t new_size = users_ptr->user[index_max_W].id.assigned_RBs;

users_ptr->user[index_max_W].id.RB_number = realloc(users_ptr->user[index_max_W].id.RB_number,
new_size * sizeof *users_ptr->user[index_max_W].id.RB_number);

由于目标指针的嵌套名称,它有点笨拙。我们可以通过使用合适的临时指针变量来删除重复的复杂访问来简化它:

usu *user = &users_ptr->user[index_max_W];
user->id.assigned_RBs++;
user->id.RB_number = realloc(user->id.RB_number,
                             user->id.assigned_RBs * sizeof *user->id.RB_number);