pointers

I was asked to find out the output of the following program...but i think it is a wrong question...answer given says it would print
2,0

Can anyone please explain...
1
2
3
4
5
6
7
8
9
10
11
12
13
#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;
}
You didn't say exactly what the program is expected to do (explain the algorithm), so how do u expect to get an answer?
And you cannot convert integer array to char in assignment and Vice versa.
The program has undefined behavior because of lines 7, 9, 10, and 11. In other words, it can do anything.

If we assume that the program actually does what the programmer thought it would do, it's because of pointer arithmetic. Casting an 'int *' to a 'char *' "converts" (so to speak) the pointed-to array to an array of chars. In memory, the int array looks like this (separated by bytes):
02 00 00 00 03 00 00 00 04 00 00 00
The expression p+1 evaluates to a pointer that is 1 char in front of p. So the old p pointed to the char 02, and the new one points to the 00 next to it.

Lines 9 and 11 are particularly nasty. Dereferencing a pointer of one type as a pointer of another type at least has (if you do it right) no chance of smashing the stack.
With the way printf() works internally (with variadic functions), telling printf() that you're passing an int (with "%d") and then passing something else entirely can wreak havoc in the stack and your program can end up executing data as if it was code, leading to very bad things.
If you ever need to print a char as if it was an int, make an explicit cast:
1
2
//char c;
printf("%d", (int)c);


I bet whoever wrote this thought they were being pretty clever, and not showcasing their own ignorance of C.
Topic archived. No new replies allowed.