Reputation: 103
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?
Upvotes: 9
Views: 4505
Reputation: 5683
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
;
Upvotes: 2
Reputation: 6126
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;
Upvotes: 6
Reputation: 399753
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
.
Upvotes: 1
Reputation: 7207
In that case (* structNAME) is pointer variable of that structure..
Upvotes: 0
Reputation: 22890
structNAME
is defined as a pointer on struct structExample
. SO you can do
structNAME tempStructPtr = malloc(sizeOf(struct structExample));
tempStructPtr->member1 = 2;
Upvotes: 1