Lurr Lurr - 27 days ago 9
C Question

typedef structure with * to the name in c

I've come across this strange way to define a structure in C and I cannot find anywhere what this really is?

typedef struct {
int val;
} *Name;


What is the difference to this?

typedef struct {
int val;
} Name;


I see however that I have to use "->" on the first and "." on the second, but what is really the difference?

Answer Source

In the first case

typedef struct {
    int val;
} *Name;

the name Name is declared as an alias for the type pointer to an unnamed structure.

You can use this pointer type for example the following way

Name ptr = malloc( sizeof( *ptr ) );

and then you can write for example

ptr->val = 10;

or

( *ptr ).val = 10;

That is in this declaration there is declared the pointer ptr of the type Name and dynamically created an object of the structure and the pointer points to this dynamically created object.

In the second case

typedef struct {
    int val;
} Name;

the name Name is declared as an alias for the unnamed structure itself.

To declare an object of this type you can just write

Name name;

and then

name.val = 10;

or just

Name name = { 10 };

and an object of the structure type will be created.

Or if you want to allocate an object of the structure type dynamically you can write

Name *ptr = malloc( sizeof( Name ) );

To make it more clear here are another examples of using typedef.

typedef int A[10];

this typedef declares the name A as an alias for the array type int[10].

you can write after that

A a;

This declaration declares array object a of the type A that is equivalent to int[10].

This declaration

typedef int ( *A )[10];

declares the name A as an alias to the type pointer to an array of type int[10].

This declaration can be used for example the following way

int a[10];
A ptr_a = &a;