#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
shortarray 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
xYou cast the base address of
xand assign it to thecharpointercp. Theprintf()sees a character in*xwhose size is1byte.xpointed to byte 0 and so doescpbut in the case of the latter, only1byte is considered assizeof(char)is1.The content at byte 0 happens to be
0x02.So,
prints
2.spis ashortpointer, the same type asx. So*spwould print the same thing as*x. It will consider the first2bytes from the given address.sppoints to byte0. So bytes0and1will be considered. Therefore, the value is0x0102which is printed bycpstill points to byte0.cp[3]is effectively*(cp+3). Sincecpis acharpointer,cp+3will point to0 + 3*sizeof(char)which is0 + 3*1which in turn is byte3.At byte
3, we have0x11and only a single byte is considered assizeof(char)is1.So,
will print
11In
The integer pointer
ipis assigned the base address ofx. Thenipis incremented by1.ipinitially pointed to byte 0. Sinceip+1will point to byte0 + 1*sizeof(int)which is0 + 1*4which in turn is byte 4.So
ipnow 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+6points to byte 6 the content of which is32.Hence,
prints
32.spafter adding5to it, now points to byte0 + 5*sizeof(short)which is0 + 5*2which in turn is byte 10 the content of which after considering 2 bytes (bytes 10 & 11) is5152.*cp's value is0x02.*cp + 2is0x02 + 0x02=0x04=0x0004.This value is assigned to the integer pointed to by
*x(bytes 0 & 1).So byte 0 is now
0x04and byte 1 is now0x00.cp[1]is*(cp+1).cp+1points to byte 1 the content is now0x00which is printed whenis done.