所以,我在其他结构中有一个结构..我想知道我怎么才能锁定那个结构。
#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;
}所以,我试过了,但是,不是工作..我如何才能做到这一点,还是更好的分配所有结构?
发布于 2013-09-08 06:57:54
你只需要分配Str1,Str2会自动分配。在我的系统上,Str1的大小是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);
}发布于 2013-09-08 06:51:32
为什么不像下面这样声明:
typedef struct
{
int a, b, c;
}Str2;
typedef struct
{
int n, o, p;
Str2 s2;
}Str1;然后,您可以根据需要单独分配它们。例如:
Str2 *str2 = (Str2*)malloc(sizeof(Str2));
Str1 *str1 = (Str1*)malloc(sizeof(Str1));
s1->s2.a = 0; // assign 0 to the a member of the inner Str2 of str1.发布于 2013-09-08 06:51:41
Str1和Str2是您声明的匿名struct的对象,所以语法是错误的。你是不是忘了一些typedefs?
//declares a single object Str1 of an anonymous struct
struct
{
}Str1;
//defines a new type - struct Str1Type
typedef struct
{
}Str1Type;https://stackoverflow.com/questions/18678661
复制相似问题