They both do "cout << my_char_pointer". In the first case it doesn't do what you want, in the second, it does. Whoever built C++ standard library decided that the second case is going to be more common (obviously).
If you want to get the numeric vaule of a char*, do "cout << (void*)s;"
Thanks guys!
Yes, I wanted to find out what the address is of a single char point. Because it has to be somewhere in the memory.
Hamsterman, thanks, I tried "cout<<(void*)s;", and it worked.
But could you explain it why the simple "s" makes a nonsense on the output and "(void*)s" gives me the address I need?
Thanks again, it was a big help.
The << operator behaves differently depending on what type of variable you give it. See my previous post. In both cases s is a pointer to char, so it is natural that << will behave the same way. It has no way to know that the first one is a pointer to a single char and the second one is to an array. So cout << any_char_pointer; will try to print a string that the pointer points to.
Likewise, cout << any_other_pointer; will print the address the pointer points to in hexadecimal. Also, cout << any_integer; will print the decimal representation of the value stored in any_integer.
Which is why (int)s looks different from (int*)s. The only difference is that the first one is in decimal and the second one - in hexadecimal (which is marked be a 0x prefix).
Thanks.
Probably I am stupid to understand it but I don't know why the simple "s" doesn't give me the hexadecimal address and why "(void*)s" or "(int*)s" does?
Since "*s" should give back the value stored in pointer s and "s" should give back the address the pointer s pointing to.
So where from "s" gives me that strange output?
w♂ ( w
I am not going to ask more question!
:)
Thanks a lot!
#include <iostream>
void foo(int f) {
std::cout << "foo has been passed an integer\n";
}
void foo(void* f) {
std::cout << "foo has been passed a pointer to something\n";
}
void foo(char* f) {
std::cout << "foo has been passed a string\n";
}
int main(){
char ch = 'w';
int i = 5;
foo(i);
foo(&i);
foo(ch);
foo(&ch);
foo("hello");
}
Overloading operators works the same way. It is for designers of standard library to decide what and how is printed.