Reputation: 311
I apologize in advance for the silliness of this question. But I couldn't find the way of understanding this outcome. I'm trying to figure out what the pointer really is in C++. Following is just a simple code printing an address in different ways.
int a = 15000;
char *b = reinterpret_cast<char*>(a); //equivalent of char *b = (char *)a
int *m = &a;
//(1)
printf("&a:%p\n",&a); //0x7fff5fbff878
printf("&*m:%p\n",&*m); //0x7fff5fbff878
printf("m:%p\n",m); //0x7fff5fbff878
//(2)
printf("a:%p\n",(int*)a); //0x3a98
printf("&*b:%p\n",&*b); //0x3a98
printf("b:%p\n",b); //0x3a98
printf("*m:%p\n",(int*)*m); //0x3a98
printf("&b:%p\n",&b); //0x7fff5fbff870
printf("&m:%p\n",&m); //0x7fff5fbff868
//(3)
std::cout << "b:" << b << std::endl; //error: Segmentation fault: 11
So the question is
Upvotes: 2
Views: 165
Reputation: 3527
why the address of (1) and (2) are different
Because in the first example (1), you use the &
address of operator, which gives you the address where the "a" variable is stored, example 0x50302040
.
But the second example (2), you are using the value that address (0x50302040
) points to, which returns 15000 which equals to 0x3a98 in hexadecimal.
what happened when an int is cast to a char*
If int
has a value of 15000, now char*
points to the address 15000
, which is clearly wrong.
why the error (3) has occurred while 'printf("b:%p\n",b)' is working.
Because your pointer is a char*
pointer, therefore the character sequence overload (ostream& operator<< (ostream& os, const char* s);
is used, and since your pointer doesn't point to a character sequence (in fact, it doesn't point to anything since you assigned an invalid value to it), your program crashes.
Theres a ostream& operator<< (void* val);
overload that will just print the address of the pointer, but you need to explicitly cast your char*
pointer to a void*
pointer to use it:
std::cout << "b:" << (void*)b << std::endl; // Prints 0x3a98 (15000)
Upvotes: 3