This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Accessing the variable within the union

Hi,

We are defining the union and structures mentioned below


typedef struct _var1_
{
int a;
int b;
}var1_t;

typedef struct _var2_
{
int c;
int d;
}var2_t;

typedef union _UVar
{
var1_t stVar1;
var2_t stVar2;
}UVar;

Created the instance like below.

UVar uVar;
UVar *puVar = &uVar;

Trying to access the element 'a ' as explained in below method

Method 1:

Accessing the  element  'a'  like below

puVar->stVar1.a 

was not working.

Method 2:

But typecasting the union pointer to the structure 

((var1_t*)puVar)->a ;

was working.

In most part of the code in our application, use method 1.

Why method 1 was not working? 

Is any configuration to be done to access the elements within the union?

Thanks & Regards,

K. lakshmanan