澄清C struct语法

时间:2013-05-13 12:16:21

标签: c struct

像往常一样,Wikipedia's article on structs不太明确。它给出了结构的语法:

[typedef] struct [struct_name]
{
    type attribute;
    type attribute2;
    /* ... */
    [struct struct_name *struct_instance;]
} [struct_name_t] [struct_instance];
  • typedef关键字在这里做什么?
  • [struct_name]是什么意思? (它是您给新结构数据类型的名称吗?)
  • [struct_name_t]是什么意思?
  • [struct_instance]是什么意思? (它是否创建了结构的单个实例?)
  • 我假设[struct struct_name *struct_instance;]在结构中创建一个指向结构的第二个实例的指针。正确的吗?

我非常感谢一个例子:说我有三个文件:main.c,sub.c和sub.h.我想在sub.h中声明一个struct的实例,并在sub.c中实例化并使用它。假设我想要一个歌曲类型结构,成员char name[20]char artist[10],并说我想创建一个实例,mySong,{“我唱歌”,“我”},这看起来怎么样子.c和sub.h?

由于

4 个答案:

答案 0 :(得分:3)

•What would the typedef keyword do here?

它允许您创建结构的typedef,就像任何其他类型一样。这样您就不必每次都输入struct xxx struct_name。你不需要这个,因此[]

•What does the [struct_name] mean? (Is it the name you're giving to the new struct data type?)

是的,如果你也选择了。您还可以创建一个无名结构,这样您就不需要为它命名。

•What does the [struct_name_t] mean?

如果你选择输入结构

,那就是typedef名称

•what does the [struct_instance] mean? (Is it creating a single instance of the struct?)

是的,它用于创建一个或多个sturct实例

•I presume [struct struct_name *struct_instance;] creates a pointer in the struct which would point to a second instance of the struct). Correct?

是的,这对于链表中的“下一个”类型指针很有用。

struct example:

typedef struct foo{
    int count;
    struct foo *next;
} foo_t myfoo;

是填写的一个例子;这允许您通过以下方式声明一个新结构:

 foo_t new_foo_struct;

因为typedef和typedef'd名称。如果你省略这样的话:

struct foo{
    int count;
    struct foo *next;
} myfoo;

现在,您必须为每个实例使用struct关键字,例如:

 struct foo new_foo_struct;

将其分解为多个文件:

/*sub.h*/
typedef struct{
char name[20];
char artist[10];
}song;

然后在来源:

/*sub.c*/
#include "sub.h"

/*this needs to go into a function or something...*/
song mysong;
strcpy(mysong.name, "Mesinging");
strcpy(mysong.artist, "Me");

答案 1 :(得分:2)

那篇文章错误地混合了不同的概念,现在纠正了这一点。结构是通过

声明的
struct tagname {
  ... fields ...
};

就是这样,只有tagname部分在某些情况下是可选的。

另外你可以

  • 通过struct
  • 声明typedef类型的别名
  • struct类型的变量

“一气呵成”,但我不认为它是好的风格,应该分开。

答案 2 :(得分:1)

sub.h
------
typedef struct{
char name[20];
char artist[10];
}song;


sub.c
----
song mysong={"Me Singing","Me"};

答案 3 :(得分:0)

typedef struct struct_name
{
   char name[20];
   char artist[10];
}struct_name_t structInstance; 

typedef - 这意味着您正在创建一个新类型(struct_name_t

因此,在C代码中,您可以创建一个这样的实例:

struct_name_t myVariable;

或者您可以明确地写:

struct struct_name myVariable;

最后的structInstance表示您希望在定义结构的同一时刻创建结构的实例(该变量的名称是structInstance)。这不是你会一直使用的东西,但在某些情况下它很有用。

如果要创建结构的实例并在创建时分配/初始化成员,可以这样做:

struct_name_t myVariable = { "Foo", "bar" };

'name'成员将包含“Foo”,艺术家成员将包含“bar”。

注意: 如果你这样写:

struct_name_t myVariable = { 0 };

这将用零填充整个结构!