pointer is not printing correct value

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

fffffffffffe701 
, 33752069 
, 2
Last edited on
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 ...
Thank you so much ,I got the point.
I dont understant it


1
2
3
4
5
6
7
8
9
10
11
int _tmain(int argc, _TCHAR* argv[])
{
	char c[] = { 1 , 2,3 ,4 , 5, 6 , 7 , 8 , 9 , 10 } ; 
	char *p = (char*) &c[0] ; 
	
	cout<<"\n Address =  \t "<<p ; 
	cout<<"\n Pointer Variable = \t"<<(char* )p[0];
	cout<<"\n Variable = "<<c[0];

	return 0;
}


also give me wrong answer .
@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)
Change the computer!:) For example I have a computer that gives me the correct answer.
Last edited on
cout<<"\n Pointer Variable = \t"<<(char* )p[0];

p[0] is a char. Casting it to a char* is a bad cast, hence why you get bad output.
Change your code the following way


1
2
3
4
5
6
7
8
9
10
11
int _tmain(int argc, _TCHAR* argv[])
{
	char c[] = "12345678910" ; 
	char *p = &c[0] ; // or char *p = c;
	
	cout<<"\n Address =  \t "<< ( void * )p ; 
	cout<<"\n Pointer Variable = \t"<<p[0];
	cout<<"\n Variable = \t"<<c[0];

	return 0;
}


and you will get a valid result.
Last edited on
Topic archived. No new replies allowed.