Search code examples
cstructtype-declaration

Type Declarations in C ( Conceptual )


This question is in general more of a conceptual question and not a coding problem essentially. I was curios as I came across these pieces of code and was wondering if they are valid or not. Or why basically , if someone could give me an explanation please ?

Here are some type declarations in C:

typedef struct Rec1 * Ptr1;
typedef struct Rec2 * Ptr2;

struct Rec1
{
    int data;
    Ptr2 next;
};

struct Rec2
{
    double data;
    Ptr2 next;
};

Should these be allowed? Are they allowed? Why or why not?


Solution

  • Are they valid?

    Yes they are valid

    Reason:

    1. First two lines create Ptr1 and Ptr2 as type-definitions for a struct Rec1 * and struct Rec2 *.

    2. Since they are pointers, and not structures themselves, they make the struct Rec1 and struct Rec2 as incomplete types, and they are just making Rec2 as recursive type (usually used in creating datastructures) and Rec1 as having a pointer to Rec2 object.

    Should they be allowed?

    How else can you create self-referencing structures?