#include <stdio.h>
int main(void)
{
char *cp;
short *sp;
int *ip;
short x[6];
int i, y;
y = 0x0102;
for (i = 0; i < 6; i++)
{
x[i] = y;
y = y + 0x1010;
}
cp = (char*) x;
printf("1) *cp = %x\n", *cp);
sp = x;
printf("2) *sp = %x\n", *sp);
printf("3) cp[3] = %x\n", cp[3]);
ip = (int*) x;
ip = ip + 1;
printf("A) *ip = %x\n", *ip);
printf("B) cp[6] = %x\n", cp[6]);
sp = sp + 5;
printf("C) *sp = %x\n", *sp);
*x = *cp + 2;
printf("D) cp[1] = %x\n", cp[1]);
return 0;
}
I do not understand how the short array is typecasted to a char, and what happens when the typecast happens. Could someone kindly help me out with this !!
You declared a
short
array of 6 elements namedx
.You assigned values into each of these elements. The initial values would be:
I'm making a few assumptions here but modify them if that's not your case.
So in memory, it would look like
where the
x
You cast the base address of
x
and assign it to thechar
pointercp
. Theprintf()
sees a character in*x
whose size is1
byte.x
pointed to byte 0 and so doescp
but in the case of the latter, only1
byte is considered assizeof(char)
is1
.The content at byte 0 happens to be
0x02
.So,
prints
2
.sp
is ashort
pointer, the same type asx
. So*sp
would print the same thing as*x
. It will consider the first2
bytes from the given address.sp
points to byte0
. So bytes0
and1
will be considered. Therefore, the value is0x0102
which is printed bycp
still points to byte0
.cp[3]
is effectively*(cp+3)
. Sincecp
is achar
pointer,cp+3
will point to0 + 3*sizeof(char)
which is0 + 3*1
which in turn is byte3
.At byte
3
, we have0x11
and only a single byte is considered assizeof(char)
is1
.So,
will print
11
In
The integer pointer
ip
is assigned the base address ofx
. Thenip
is incremented by1
.ip
initially pointed to byte 0. Sinceip+1
will point to byte0 + 1*sizeof(int)
which is0 + 1*4
which in turn is byte 4.So
ip
now points to byte 4. Since it is an integer pointer, 4 bytes are considered - namely bytes 4, 5, 6 & 7 the content of which is31322122
.cp[6]
means*(cp+6)
.cp+6
points to byte 6 the content of which is32
.Hence,
prints
32
.sp
after adding5
to it, now points to byte0 + 5*sizeof(short)
which is0 + 5*2
which in turn is byte 10 the content of which after considering 2 bytes (bytes 10 & 11) is5152
.*cp
's value is0x02
.*cp + 2
is0x02 + 0x02
=0x04
=0x0004
.This value is assigned to the integer pointed to by
*x
(bytes 0 & 1).So byte 0 is now
0x04
and byte 1 is now0x00
.cp[1]
is*(cp+1)
.cp+1
points to byte 1 the content is now0x00
which is printed whenis done.