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?
You can use typedef to give a name to your user defined data types as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows −
A typedef declaration is a declaration with typedef as the storage class. The declarator becomes a new type. You can use typedef declarations to construct shorter or more meaningful names for types already defined by C or for types that you have declared.
In C++, there is no difference between 'struct' and 'typedef struct' because, in C++, all struct/union/enum/class declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name.
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
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With