Reputation: 109
I'll start by cataloging what I know to distinguish that from what I want:
astruct mystruct;
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
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
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
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