所以,我在其他结构中有一个结构..我想知道如何 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/