2015-09-15 57 views
5

在C中,定义结构时。什么是创建新实例的正确方法?我已经看到了两种方式:如何在C中创建结构的新实例C

struct listitem { 
    int val; 
    char * def; 
    struct listitem * next; 
}; 

第一种方式(Xcode中说,这是重新定义了结构和错误):

struct listitem* newItem = malloc(sizeof(struct listitem)); 

第二种方式:

listitem* newItem = malloc(sizeof(listitem)); 

或者,是有另一种方法吗?如果一个变量与listitem类型的任何声明之前使用

typedef struct listitem listitem; 

+4

*“(xCode说这是重新定义结构和错误)”*。有些东西你没有告诉我们,因为第一种方法既没有重新定义结构也没有错。 – user3386109

+0

@ user3386109哦,你是对的! XCode只是说它是错误的,因为我在函数中使用它,而不是main()。不知道为什么...... –

回答

8

第二种方法只适用。你也可以静态分配的结构,而不是动态分配的:

struct listitem newItem; 

你已经证明的方式是像做每一个int下面要创建:

int *myInt = malloc(sizeof(int)); 
+0

这个简单的约定总是:“typedef Foo_tag {...} Foo_t”和使用“Foo_t”随即在C编程中工作得很好。 “typedef”实际上只有打字费用,但之后它通过永远不必输入“struct Foo_tag”来进行分解。 – BitTickler

+0

'struct listitem newItem;'只在文件范围发生时才是静态分配。在块范围这是自动分配。 –

+0

@MM你当然是对的,但一般来说,'malloc'和朋友处理动态分配,而其他形式的分配,无论在文件中的位置,通常被称为“静态分配”来区分它动态分配。 –

7

这取决于您是否需要指针。

最好是打电话给你的结构是这样的:

Typedef struct s_data 
{ 
    int a; 
    char *b; 
    etc.. 
}    t_data; 

后,以实例化它无指针结构:

t_data my_struct; 
my_struct.a = 8; 

如果你想有一个指针,你需要的malloc像那:

t_data *my_struct; 
my_struct = malloc(sizeof(t_data)); 
my_struct->a = 8 

我希望这个答案对您的问题