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 4 of 9.

TDas said:   6 years ago
Cannot convert an integer to a character pointer.

So,to get the desired output the revised code should be p=(char*)arr in place of p=arr and p=(char*)(int*)(p+1) in place of p=(int*)(p+1) .
(2)

Danny said:   1 decade ago
Hey so I have a doubt like if you cast a pointer like this.

(int *)p+1;

That means you are adding 4 byte to that address and go to the next one is 3;

Can anybody explain this?

Rookie said:   1 decade ago
It causes a compile time error as it is an incompatible type conversion p being an character pointer is referring to int base array.

Anyone please explain the correct logic.

Vijay Singh said:   1 decade ago
It's give error in turbo c3
p = arr; \\ can not convert "int *" to "char *"
p = (int*)(p+1); \\ can not convert "int *" to "char *"

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.

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.

Pankaj said:   1 decade ago
I tried to run this program but it gives compiletime error:
"suspicious pointer conversion" for below lines
p = arr;
p = (int*)(p+1);

Sundar said:   2 decades 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.

Sarala said:   1 decade ago
It causes a compile time error as it is an incompatible type conversion p being an character pointer is referring to int base array.

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.


Post your comments here:

Your comments will be displayed after verification.