zonelincosmos
zonelincosmos

Reputation: 55

How to define a structure with a pointer-type item?

I have a typedef struct but with a pointer type naming *Ptype as shown below -

typedef struct
{
    int InputIntArg1;
    int InputIntArg2;
    char InputCharArg1;
} *Ptype;

I want to define an item (Item1) and assign numbers to its members(InputIntArg1 & InputIntArg2). However, Item1 is a pointer. Is it possible not to change the typedef naming (*Ptype) and do a correct declaration?

int main(void)
{
    Ptype Item1; // <---------- How to modify this line?
    Ptype Item2;

    Item1.InputIntArg1 = 1;
    Item1.InputIntArg2 = 7;
    Item2 = &Item1;
    printf("Num1 = %d \n", Item2->InputIntArg1);
}

Upvotes: 1

Views: 71

Answers (2)

Stephan Schlecht
Stephan Schlecht

Reputation: 27126

I would not hide a pointer to a struct with a typedef.

Perhaps use:

typedef struct
{
    int InputIntArg1;
    int InputIntArg2;
    char InputCharArg1;
} Type;

Then you can write:

int main(void)
{
    Type Item1;
    Type *Item2;

    Item1.InputIntArg1 = 1;
    Item1.InputIntArg2 = 7;
    Item2 = &Item1;
    printf("Num1 = %d \n", Item2->InputIntArg1);
}

So what happens then:

  • Item1 is a Ptype struct
  • Item2 is a pointer to a Ptype struct
  • with the assignment Item2 = &Item1; Item2 points now to the Item1 struct
  • using the Item2 pointer you are now accessing the values of the Item1 struct

Upvotes: 1

Unn
Unn

Reputation: 5098

No, there isn't a way to refer to the anonymous struct type itself from just Ptype. The best you can do is add the base type and pointer types in the same type definition:

typedef struct
{
    int InputIntArg1;
    int InputIntArg2;
    char InputCharArg1;
} type, *Ptype;

Then just use type for the actual struct and Ptype for a pointer to it.

Upvotes: 1

Related Questions