c - 如何仅通过一次 malloc 调用来分配嵌套数据结构?

标签 c data-structures malloc

我想分配下面定义的嵌套数据结构,只用一次 malloc 调用。在 C 中有可能吗?如果可以,我该怎么做?

struct s1 {
    int a;
    int b;
    char ns1[16];
};

struct s2 {
    struct s1 *ps1;
    int i;
    int j;
    char ns2[16];
};

最佳答案

这不是嵌套结构,因为 ps1 是指针,不是结构。

malloc() 可以很好地处理指针。您可以毫无问题地分配 s2。但是您必须将 ps1 成员指向有效的内容。

嵌套结构看起来更像这样:

struct s2 {
    struct s1 x_s1;
    int i;
    int j;
    char ns2[16];
};

malloc() 也应该没问题。

关于c - 如何仅通过一次 malloc 调用来分配嵌套数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25634203/

相关文章:

c++ - 在 Windows 构建中使用 pthread.h

c 指向结构体的指针问题

c - libcurl (7.19,7) 在 OSX (10.6.8) 上因 _mdns_query_callback 而崩溃

c - C 中的 getField 方法

algorithm - 谷歌采访 : Find the maximum sum of a polygon

algorithm - 与后缀树的隐式表示匹配的字符串

python - 列表中大于 x 的数字序列的长度

c - 多线程读取文件

c - 释放 getline() 缓冲区后丢失的字节

c - 为什么我不应该在 malloc() 未分配的变量上调用 free()?