c - 如何分配结构的结构?

标签 c malloc

所以,我在其他结构中有一个结构..我想知道如何 malloc 该结构...

#include <stdio.h>
#include <string.h>

struct 
{
    int n, o, p;
    struct
    {
        int a, b, c;
    }Str2;
}Str1;

main()
{
   struct Str1.Str2 *x (Str1.Str2*)malloc(sizeof(struct Str1.Str2*));

   x->a = 10;
}

所以,我试了一下,但是,没用.. 我该怎么做,或者更好地分配所有结构?

最佳答案

你只需要分配 Str1 和 Str2 会自动分配。在我的系统上,Str1 的 sizeof 是 24,等于 6 个整数的大小。试试这个:

typedef struct {
int n;
int o;
int p;
struct {
      int a;
      int b;
      int c;
      }Str2;
}Str1;

main()
{
     Str1 *x = (Str1 *)malloc(sizeof(Str1));
     x->Str2.a = 10;
     printf("sizeof(Str1) %d\n", (int)sizeof(Str1));
     printf("value of a: %d\n", x->Str2.a);
}

关于c - 如何分配结构的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18678661/

相关文章:

c - glibc 已弃用的 __malloc_hook 功能的替代方案

c - 是否可以在 C 程序中硬编码共享库位置?

python - 将 numpy 数组传递给 cython 中的 C 函数

c - 不确定如何修复我收到的警告

c - 关闭文件时出现"Double free or corruption(out)"?

c - 当记录增加时 Malloc 失败

c - 使用双指针而不是单指针

c - 统一测试时忽略用户输入

c - 为什么我的代码中的第二个 strcpy() 导致停止工作?

c - malloc 不添加新内存