[英]What does `*` mean in a C `typedef struct` declaration?
I'm looking at a C
struct with some syntax I've never seen before. 我正在看一个
C
结构,其中包含一些我以前从未见过的语法。 The structure looks like this: 结构如下所示:
typedef struct structExample {
int member1;
int member2
} * structNAME;
I know that normally with a structure of: 我知道通常具有以下结构:
typedef struct structExample {
int member1;
int member2
} structNAME;
I could refer to a member of the second struct definition by saying: 我可以通过以下方式引用第二个结构定义的成员:
structNAME* tempStruct = malloc(sizeof(structNAME));
// (intitialize members)
tempstruct->member1;
What does that extra *
in the the first struct definition do, and how would I reference members of the first struct definition? 第一个结构定义中的额外
*
是什么,以及如何引用第一个结构定义的成员?
It means the defined type is a pointer type. 这意味着定义的类型是指针类型。 This is an equivalent way to declare the type:
这是声明类型的等效方法:
struct structExample {
int member1;
int member2;
};
typedef struct structExample * structNAME;
You would use it like this: 你会像这样使用它:
structNAME mystruct = malloc (sizeof (struct structExample));
mystruct->member1 = 42;
The typedef makes these two statements the same typedef使这两个语句相同
struct structExample *myStruct;
structName myStruct;
It makes structName
stand for a pointer to struct structExample
它使
structName
代表struct structExample
的指针
As an opinion, I dislike this coding style, because it makes it harder to know whether a variable is a pointer or not. 作为一种观点,我不喜欢这种编码风格,因为它更难以知道变量是否是指针。 It helps if you have
如果你有,它会有所帮助
typedef struct structExample * structExampleRef;
to give a hint that it is a pointer to struct structExample
; 提示它是
struct structExample
的指针;
structNAME
is defined as a pointer on struct structExample
. structNAME
被定义为struct structExample
上的指针。 SO you can do 所以你可以做到
structNAME tempStructPtr = malloc(sizeOf(struct structExample));
tempStructPtr->member1 = 2;
The secret to understanding these is that you can put typedef
in front of any declaration, to turn TYPENAME VARIABLENAME
into typedef TYPENAME ALIASEDNAME
. 理解这些的秘诀是你可以将
typedef
放在任何声明的前面,将TYPENAME VARIABLENAME
变成typedef TYPENAME ALIASEDNAME
。
Since the asterisk can't be part of the VARIABLENAME
part if this was a plain declaration, it has to be part of the type. 由于星号不能是
VARIABLENAME
部分的一部分,如果这是一个普通的声明,它必须是该类型的一部分。 An asterisk following a type name means "pointer to" the preceding type. 类型名称后面的星号表示“指向”前一类型的“指针”。
Compare this: 比较一下:
typedef int * my_int_pointer;
It's exactly the same, except in your case instead of int
you're declaring a struct
. 它完全相同,除了你的情况而不是
int
你声明一个struct
。
在那种情况下(* structNAME)是该结构的指针变量..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.