c - 嵌套结构的动态数组成员

标签 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。

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

最佳答案

realloc() 的大小参数以字节为单位,就像 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);

关于c - 嵌套结构的动态数组成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21523476/

相关文章:

c++ - 同一文件流中的 fread 和 fgetc 不起作用

java - 如何在java中使用C库

c - 如何将结构从 Matlab 代码转换为 C 代码(使用 Matlab 编译器)

delphi - 将 TArray<X> 类型转换为 X 数组是否安全?

javascript - 修改嵌套的 redux 状态而不发生变异

c - undefined reference `WinMain@16'collect2.exe : error: ld returned 1 exit status

c - -Wall 无 -Wreturn-type

c - 在函数中使用 malloc 和结构

oop - 如何在golang中创建一个自动调用的结构方法?

C程序Strings例子结果怎么是98?