Dear Friends,
Please tell me the solution for following two line code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<stdio.h>
void main()
{
char c[10]={1,2,3,4,5,6,7,8,9,0};
int *p =(int*)&c[1];
print("%x \n, %d \n, %d\n", p, *p, c[1]);
}
output:
bfba3dbf
84148994 ( but here it should print 2 right but not printing )
2
why it is printing like that
tell me the concepts behind this, please I don't want simple solution only
There are several errors:
1. main should return int
2. printf() is misspelled as "print()"
3. %x expects unsigned int, but a pointer is passed
4. *p violates strict aliasing rules
Despite all this, your output is easily explainable: you've reinterpreted a part of your character array as an int. Apparently, on your platform, ints are 4 bytes long and are stored in little-endian order. The value you're seeing is 0x05040302, which is composed of c[1], c[2], c[3], and c[4]
To compare, on one of my big-endian machines, the program (after fixing the first 3 errors) prints
Well, I try to explain. int *p =(int*)&c[1];
On this line you are storing the address of c[1] (this is correct).
But with print("%x \n, %d \n, %d\n", p, *p, c[1]);
you are printing the value of a 4 byte value (the size of an integer on a 32 bit engine). Your pointer int *p ist storing the value of one byte (size of char on 32 bit engine).
So you have to cast the pointer value to one byte print("%x \n, %d \n, %d\n", p, (char)*p, c[1]);
I hope this gives you the kick in the right direction ...
@bluecoder Define "wrong". What were your expectations? Remeber that ostream's operator<< has an exception for pointers to char (it treats them as pointers to the first character of a null-terminated array and prints the contents of the array as a C string)