Paul A.
Paul A.

Reputation: 449

Indexing to get access members of a structure. C programming

Assuming I have a struct

typedef struct  
{ 
   unsigned char mem1; 
   unsigned char *mem2
} MEMBERS;

where

 unsigned sample = 12
 MEMBERS memvalues = {  0x15 , &sample  };

I need to access both values mem1 and mem2, when a function "GET_MEM" returns the address of the structure "MEMBERS" to X_mem. What I mean is this:

unsigned char *X_mem = GET_MEM ( );    //function returns address of memvalues
unsigned value1 = *X-mem;
unsigned Value2 = *++X_mem;

I want value1 to give 0x15, and value2 gives 12.

How can I make this work?

NOTE: Please do not assume the above code example to be syntactically correct. Its just to express my intention. Thanks Folks.

Upvotes: 1

Views: 268

Answers (3)

Lundin
Lundin

Reputation: 214780

You can't get it to work like this unless X_mem is declared as a pointer to a MEMBERS struct. To rely on address offsets from the beginning of a struct is dangerous and non-portable, since the compiler is free to add any number of padding bytes in the struct, anywhere after mem1. So the sane solution is to write MEMBERS *X_mem and then access each member through the -> operator.

If you for some reason need write code that relies on offsets like this, you need to ensure that the "padding byte pattern" is as expected, or that padding is disabled entirely.

Upvotes: 1

Philip
Philip

Reputation: 1551

Yeah, have GET_MEM() return the address of the struct.

MEMBERS *X_mem = GET_MEM( );    //function returns address of memvalues
unsigned char value1 = X_men->mem1;
unsigned char Value2 = *(X_mem->mem2);

Upvotes: 1

unwind
unwind

Reputation: 400039

You need to cast the incorrectly typed pointer returned by GET_MEM():

const MEMBERS *some_members = (MEMBERS *) GET_MEM();
unsigned value1 = some_members->mem1;
unsigned value2 = *some_members->mem2;

Upvotes: 1

Related Questions