我想分配下面定义的嵌套数据结构,只有一个malloc调用。在C中有可能吗?如果是这样,我该怎么做?
struct s1 {
int a;
int b;
char ns1[16];
};
struct s2 {
struct s1 *ps1;
int i;
int j;
char ns2[16];
};
答案 0 :(得分:1)
这不是嵌套结构,因为ps1
是指针,而不是结构。
malloc()
可以正常使用指针。您可以毫无问题地分配s2
。但是你必须将ps1
成员指向有效的东西。
嵌套结构看起来更像是这样:
struct s2 {
struct s1 x_s1;
int i;
int j;
char ns2[16];
};
并且malloc()
也应该对那个也没关系。
答案 1 :(得分:1)
一次为多个对象分配空间的可移植方法是将它们包装到容器结构中:
struct PairHolder
{
struct s2 first;
struct s1 second;
};
// Postcondition: You own the result and must call free() on it (and on nothing
// else).
struct s2 * create_s2_and_s1()
{
struct PairHolder *ph = malloc(sizeof(PairHolder));
ph->first.ps1 = &ph->second;
return &ph->first;
}
答案 2 :(得分:0)
经过一天的研究,并根据以前的答案。我想出了下面的解决方案。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct s1 {
int a;
int b;
char ns1[16];
};
struct s2 {
struct s1 *ps1;
int i;
int j;
char ns2[16];
};
int main(int argc, char *argv[])
{
struct s2 *ps2;
ps2 = malloc(sizeof(struct s1) + sizeof(struct s2));
ps2->ps1 = (struct s1 *)(ps2 + 1);
ps2->ps1->a = 1;
ps2->ps1->b = 2;
strcpy(ps2->ps1->ns1, "s1");
ps2->i = 3;
ps2->j = 4;
strcpy(ps2->ns2, "s2");
free(ps2);
return 0;
}