Scott Fagen
Scott Fagen

Reputation: 109

In C, is there a way to declare an instance of a structure that is always addressed by a particular pointer?

I'll start by cataloging what I know to distinguish that from what I want:

  1. I can declare a "template" for a structure through `typedef struct astruct...'
  2. I can declare an instance of a structure, in global or local storage, through astruct mystruct;
  3. I can declare a pointer to a structure through astruct *pmystruct; and then set the value of that pointer to an instance through pmystruct = &mystruct;

What I'd like is to do sort of the opposite of #3: I'd like to declare an instance of a structure that is defined to be addressed by a particular pointer...something akin to:

astruct *pthestruct;
astruct thestruct referencedby(pthestruct);

Then, I would not need to prefix any reference to a field within the struct with pthestruct -> thestruct.structdataitem

This is accomplished in PL/I by using the BASED attibute on the declaration:

DCL PTHESTRUCT POINTER;
DCL 1 THESTRUCT BASED(PTHESTRUCT),
      3 ... (rest of the structure) ;

In the code all references to THESTRUCT will be implicitly "based" off the address in PTHESTRUCT, just as if I had coded PTHESTRUCT -> THESTRUCT.

Ideas?

Thanks, Scott

Upvotes: 0

Views: 55

Answers (3)

pmg
pmg

Reputation: 108988

Do you mean

struct whatever object[1];

You can now use the object itself

object[0].field = 42;
foo(object[0]); // pass a copy

or the (array converted to) pointer

object->field = 42;
bar(object); // pass a pointer

Upvotes: 0

Eric Postpischil
Eric Postpischil

Reputation: 223747

If you want thestruct to refer to the *pstruct for the value of pstruct at the time of assignment/definition of thestruct, then C++ has this in its references feature, but C does not.

If you want thestruct to refer to *pstruct for the value of pstruct at the time thestruct is used, then this can be accomplished with a macro:

#define thestruct (*pstruct)

In many circumstances, this would be considered bad practice.

Upvotes: 2

ChrisBD
ChrisBD

Reputation: 9209

Do you mean ?

  typedef struct
    {
     int a;
     int b;
    } struct_t;

    struct_t myStruct;
    struct_t* pStruct;

   pStruct = &myStruct;
   pStruct->a =5;

Upvotes: -1

Related Questions