繁体   English   中英

为Union动态分配内存

[英]Dynamic memory allocation for Union

例如,我有一个以下类型的联合

typedef union
{
     typedef struct
     {
          short int a;
          short int b;
          short int c;
          short int d
     }str1;
     short int my_array[x];
}union1; 

在这里,我想动态地将内存分配给数组,这将永远超过str1需求。 我需要在上面的代码中进行哪些更改,以便能够动态地将内存分配给my_array

我要做的是使my_array成为指针,如下所示:

 typedef union
 {
     struct
     {
         short int a;
         short int b;
         short int c;
         short int d;
     } str1;
     short int *my_array;
 } union1; 

这样,您可以:

union1 foo;
foo.my_array = malloc(bar * sizeof(short int));

我删除了您使用的内部typedef ,因为它没有任何作用并导致编译器错误。 我认为您打算使用匿名struct

您可以使用它,但是请注意,您将无法使用union1数组:

typedef struct
{
    short a;
    short b;
    short c;
    short d;
}
str1;

typedef union
{
    str1  my_str;
    short my_array[0];
}
union1;

union1* allocate_union1(int additional_size)
{
    return (union1*)malloc(sizeof(union1)+additional_size);
}

如果收到[0]的编译器警告,则可以将其替换为[1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM