Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

struct

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?

like image 928
Osley Avatar asked Mar 25 '13 13:03

Osley


People also ask

What does typedef struct mean in C?

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 −

What is typedef declaration in C?

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.

What is difference between typedef and struct?

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.


2 Answers

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;
like image 177
harald Avatar answered Oct 06 '22 21:10

harald


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;

like image 33
iain Avatar answered Oct 06 '22 22:10

iain