hello lets say i have this code
你好,我说我有这个代码
typedef struct entry {
union {
struct A {
char *c;
} *A;
struct B {
char *c;
} *B;
} value;
} *TableEntry;
i m doing a malloc for entry and now i want to copy a string to c from struct A . do i have to allocate memory for struct A and then for c or the first malloc for table entry allocates for all of them ? thank you in advance
我正在做一个malloc用于输入,现在我想从struct A复制一个字符串到c。我是否必须为结构A分配内存,然后为c或第一个malloc分配表的所有内容?先感谢您
3 个解决方案
#1
3
you have to allocate memory for both of them
你必须为它们分配内存
#2
2
When you allocate the TableEntry
- you allocate the memory for the whole union. Pointers in it are allocated, but what they point to - are not. So you should assign values that you allocate to c
members of the struct and A
/B
members of the union.
分配TableEntry时 - 为整个联合分配内存。它中的指针是分配的,但它们指的是 - 不是。因此,您应该将分配的值分配给结构的c成员和union的A / B成员。
Note that the A
and B
share the same space.
请注意,A和B共享相同的空间。
#3
0
To clarify, three allocs are needed, e.g.:
澄清一下,需要三个分配,例如:
TableEntry *t = malloc(sizeof *t);
t->A = malloc(sizeof *t->A);
t->A->c = malloc(50);
This design is questionable though, as there is no way of telling which is currently active out of A
or B
. You will have to have another index or something which keeps track of whether this entry is an A
or a B
.
但是这个设计值得怀疑,因为没有办法告诉A或B当前有哪些活动。你必须有另一个索引或者某个东西来跟踪这个条目是A还是B.
#1
3
you have to allocate memory for both of them
你必须为它们分配内存
#2
2
When you allocate the TableEntry
- you allocate the memory for the whole union. Pointers in it are allocated, but what they point to - are not. So you should assign values that you allocate to c
members of the struct and A
/B
members of the union.
分配TableEntry时 - 为整个联合分配内存。它中的指针是分配的,但它们指的是 - 不是。因此,您应该将分配的值分配给结构的c成员和union的A / B成员。
Note that the A
and B
share the same space.
请注意,A和B共享相同的空间。
#3
0
To clarify, three allocs are needed, e.g.:
澄清一下,需要三个分配,例如:
TableEntry *t = malloc(sizeof *t);
t->A = malloc(sizeof *t->A);
t->A->c = malloc(50);
This design is questionable though, as there is no way of telling which is currently active out of A
or B
. You will have to have another index or something which keeps track of whether this entry is an A
or a B
.
但是这个设计值得怀疑,因为没有办法告诉A或B当前有哪些活动。你必须有另一个索引或者某个东西来跟踪这个条目是A还是B.