Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

#include <stdio.h>

int main()
{
    int arr[3] = {2, 3, 4};
    char *p;
    p = arr;
    p = (char*)((int*)(p));
    printf("%d, ", *p);
    p = (int*)(p+1);
    printf("%d", *p);
    return 0;
}

 

  • A.2, 3
  • B.2, 0
  • C.2, Garbage value
  • D.0, 0

Answer: B

Correct answer: 2, 0

p is a char *, so dereferencing it reads a single byte. The first element of the array holds 2, and on a little-endian machine the low-order byte comes first, so *p is 2.

After p+1, the pointer addresses the second byte of that same integer - not the next element, since char arithmetic advances by one byte. For the value 2 in a four-byte int, that byte is zero. The casts are decorative; what matters is that arithmetic is scaled by the pointer's type.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.