C Programming - Pointers - Discussion

Discussion Forum : Pointers - Find Output of Program (Q.No. 13)
13.
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;
}
2, 3
2, 0
2, Garbage value
0, 0
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
87 comments Page 7 of 9.

Sai said:   1 decade ago
Please explain about
p = (int*)(p+1);
printf("%d", *p);

Prateek said:   1 decade ago
p is a char. pointer and it is assigned to complete address of arr array. so when we write (ar+1) it take address next beyond arr array. which having value 0 of defined pointer array.

Sundar said:   1 decade ago
The char pointer only stores the first byte address of integer. So while increment the pointer the next value is to be printed as 0.

Rajadurai said:   2 decades ago
The answer is correct. We can convert int pointer to char pointer and viz versa. *p is apoint to first variable. *p+1 points the next array, so the answer is zero.

DRukus said:   2 decades ago
p is declared as a char pointer but arr is an integer array
the assignment p = arr produces a compile-time error.

Ravi said:   2 decades ago
p=arr;//here p is a character pointer. we should not assign int array base address...

Siva said:   1 decade ago
#include<iostream>
int main()
{
using namespace std;
int a[]={1,2,3};
int *p;
p=a;
p=p+1;
cout<<*p;
return 0;
}

This will return 2, why? It is similar to that of the above question.

Badareenath said:   2 decades ago
Can anybody explain this please ?

Balu said:   1 decade ago
Assume ,

arr[0] = 1000.
arr[1] = 1004.
arr[2] = 1008.

now,

p=arr; i.e p=1000.

p = (char*)((int*)(p));

At this statement character pointer p 1st typecasted to integer pointer and again typecasted to character pointer.

printf("%d, ", *p);-prints value 2.

As memory representation for little endian (lowest byte will stored 1st).

00000010 00000000 00000000 00000000

p = (int*)(p+1);-in this statement p which is char pointer is incremented by one so it is pointing at location 1001.

printf("%d", *p);-prints value 0 because at memory location 1001 value 0 is stored (according to little endian ).

Mohit said:   1 decade ago
There is a warning of converting int* to char* but, there is no error. Actually we do not follow such coding practice but for the question answer is 2, 0.


Post your comments here:

Your comments will be displayed after verification.