简体   繁体   中英

What does `*` mean in a C `typedef struct` declaration?

I'm looking at a C struct with some syntax I've never seen before. 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

struct structExample *myStruct;
structName myStruct;

It makes structName stand for a pointer to 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 ;

structNAME is defined as a pointer on 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 .

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. 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 .

在那种情况下(* structNAME)是该结构的指针变量..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM