0

Code looks like this.

#include<stdio.h>

int main(){
    int vals[2];
    char *x;
    int *v, *v2, *v3;
    vals[0] = 0x00ABCDEF;
    vals[1] = 0x12345678;

    x = (char *) &vals[0];
    v = (int *) (x + 1);
    v2 = (int *) (x+2);
    v3 = (int *) (x+3);

    printf ("%x \n", *x); /*0x EF */
    printf ("%x \n", *v); /*0x 7800ABCD */
    printf ("%x \n", *v2); /*0x 567800AB */
    printf ("%x \n", *v3); /*0x 34567800 */
}

The values in the comment is the output. could you explain how x points to EF and also v , v2, v3. what is the explanation to that. i know that one hex digit is four bits and one int can store 8 hex digits but can't understand how the x points to EF and not 00 which are the first two letters and why the last two letters and not the first two.

4rshdeep
  • 490
  • 4
  • 11

1 Answers1

2

If your system has alignment requirements, then v = (int *) (x + 1); (and the next two lines) cause undefined behaviour due to an alignment violation.

But even if they don't, *v later on causes undefined behaviour by violating the strict aliasing rule. The expression *v has type int , and it is not allowed to use this type of expression to access char objects (or in fact any objects other than int, unsigned int or const-qualified versions of those).

Undefined behaviour means that anything may happen, including nonsense output or otherwise.

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