cdata-structuresstructtypedeftype-definition

Difference between these 2 declarations of structures in C


I'm working on this project for college and they gave me a sample code to use while declaring a structure, the other one is how I declared it with the information on PowerPoints and other study material.

This is the code they gave me:

typedef struct sala local, *plocal;
struct sala {
    int id;
    int capacidade;
    int liga[3];
};

This is the code for another structure i did:

typedef struct pessoa {
    char id[15];
    int idade;
    char estado;
    int dias;
} pessoa;

Can anyone explain the difference to me ?

In my code editor "local" and "*local" appear in blue. (I use Netbeans).


Solution

  • This typedef declaration

    typedef struct sala local, *local;
    struct sala {
        int id;
        int capacidade;
        int liga[3];
    };
    

    is invalid because the name local is declared twice with different meanings: the first one as an alias for the type struct sala and the second one as an alias for the type struct sala *.

    This is the difference between the first and the second typedef declarations.:)

    As for the placement of typedef declaration then it may be placed either before a corresponding structure definition. together with structure definition or after structure definition.

    For example

    typedef struct A A;
    struct A
    {
        int x;
    };
    

    or

    typedef struct A
    {
        int x;
    } A;
    

    or

    struct A
    {
        int x;
    };
    
    typedef struct A A;
    

    An essence difference between these declarations is that if you want to refer to the defined structure inside its definition then in the second and third cases you have to use the type name struct A because the typedef name A was not yet declared.

    For example

    typedef struct Node Node;
    struct Node
    {
        int x;
        Node *next;
    };
    

    but for example

    typedef struct Node
    {
        int x;
        struct Node *next;
    } Node;