719 views

Consider the following C-code fragment running on a $32$-bit $X86$ machine:

typedef struct {
union {
unsigned char a;
unsigned short b;
} U;
unsigned char c;
}S;

S    B;
S*p=&B;
S*q=&B;
p → U.b=0x1234;
/* structure S takes 32-bits */


If M is the value of $q-p$ and $N$ is the value of $((\text{int )&} ( p \rightarrow c)) – ((\text{int})p)$, then $(M,N)$ is

1. $(1,1)$
2. $(3,2)$
3. $(1,2)$
4. $(4,4)$

edited | 719 views

We have to find $q-p$

$q$ is nothing but address of $B\left [ 5 \right ]$, say it is $1010$

and $B\left [ 4 \right ]$ is $1008.$

Then $q-p=\frac{1010-1008}{size of(int)}=1$

Now, we have to find $((int)$&$(p\rightarrow c))-((int)p)$.

Here $c$ is $char$ and typecasted to $int.$

And, $((int)p)$ is 'short int' type , it's size '4B'

So, $((int)$&$(p\rightarrow c))-((int)p)=2$

Answer will be $(3)$
0

@srestha Not able to understand the second part can you please explain it again? Thank you

0

@Pratyush Priyam Kuan

which portion ??

0

@srestha how

((int)((int)&(p→c))−((int)p)=2 ?

+1 vote
S*p=&B;

$p$ is a pointer of type "S" which points to the element at index $4$ of some array $B$.

Similarly,

$q$ is a pointer of type "S" which points to the element at index $5$ of some array $B$.

$p$ and $q$ are neighbours. By pointer arithmetic, $q-p = 1$.

Now, union is of size $2$ Bytes. Becuase the size of a union is the size of the largest field in it. (Short = $2$ Bytes, Char = $1$ Byte)

Hence, overall struct is of size $3$ Bytes.

$2$ Bytes for Union, and $1$ Byte for the unsigned char $c$.

Given that:

/* structure S takes 32-bits */

Means, struct takes $4$ Bytes. That is because of Byte alignment. See this.

So, struct looks like this:

 Union Char C Padding 2 Bytes 1 Byte 1 Byte

Because $B$ is declared as an array of $10$ elements, whose elements are of type $S$,

Hence, the overall size of array $B$ is $10*4=40$ Bytes

Suppose the starting address of the $4th$ index of $B$ is $5000$.

$p→c$ would point to $5002$

$p$ would point to $5000$.

Since both $p→c$ and $p$ are typecasted as int, and the size of an int is at least 2 Bytes, hence

$((int ) \& (p→c))–((int)p) = (5002 - 5000) / 2 = 1$

Option A is correct.