-1
 #include <stdio.h>
 int main(void)
 {
   short x[12];
   unsigned char *cp;
   short *sp;
   int *ip;
   int i;
   for (i = 0; i < 12; i++) {
     x[i] = i + 1;
   }
   cp = (unsigned char *) x;
   sp = (short *) x;
   ip = (int *) x;
   printf("1)*cp = %x\n",*cp);
   printf("A)*ip = %x\n",*ip);
   ip = ip + 2;
   printf("B)*ip = %x\n",*ip);
   cp[1]--;
   printf("C) cp[1] = %d\n", cp[1]);
   printf("D)*sp = %d\n",*sp);
   sp[3] = sp[3] + 257;
   printf("E) cp[6] = %x\n", cp[6]);
   printf("F) cp[7] = %x\n", cp[7]);
 return 0;
 }

This code produces the following output

 1)*cp = 1
 A)*ip = 20001
 B)*ip = 60005
 C) cp[1] = 255
 D)*sp = -255
 E) cp[6] = 5
 F) cp[7] = 1

Am sure about the logic behind this. Does unsigned char needs something do with the output. I am not getting why 20001 is outputted by integer pointer ip and how cp[6] is 5

Sinduja Prakash
  • 73
  • 1
  • 3
  • 7
  • [What is the strict aliasing rule and how to get around it](https://stackoverflow.com/q/98650/995714) – phuclv Oct 16 '17 at 03:02

1 Answers1

1

*ip causes undefined behaviour due to violating the strict aliasing rule. You may not use an lvalue of type int to access memory declared as short.

Since the behaviour is undefined, the entire output of the program is meaningless, so you should not worry about why any particular output happened.

M.M
  • 138,810
  • 21
  • 208
  • 365