C++ char* s help
- Momo-the-Monkey
-
Momo-the-Monkey
- Member since: Oct. 15, 2005
- Offline.
-
- Forum Stats
- Member
- Level 45
- Musician
I'm having a little difficulty understanding why this is the way it is in C++.
char *s;
s = "some string";
cout << s;
Why doesn't the assignment in the second or the reference in the third line need the * like regular pointers? Thanks in advance.
- Momo-the-Monkey
-
Momo-the-Monkey
- Member since: Oct. 15, 2005
- Offline.
-
- Forum Stats
- Member
- Level 45
- Musician
So I understand that the compiler replaces the string with a pointer, which explains the second line, but I still don't understand why the third line doesn't need the *.
- Diki
-
Diki
- Member since: Jan. 31, 2004
- Online!
-
- Forum Stats
- Moderator
- Level 13
- Programmer
At 3/14/13 08:38 PM, Momo-the-Monkey wrote: Why doesn't the assignment in the second or the reference in the third line need the * like regular pointers? Thanks in advance.
Because you only need to use * when you are declaring a pointer, not when you are assigning a value.
When you are doing:
char *s;
You're declaring a char pointer with the name "s", and when you do:
s = "somestring";
The compiler already knows that "s" is a char pointer, so it will accept any char pointer as an r-value for the assignment operator, which is precisely what is being given.
At 3/14/13 08:38 PM, Momo-the-Monkey wrote: cout << s;
This is actually a function, not an assignment; cout is just a variable, and is an instantiation of the ostream class.
In that example cout is using << as an overloaded operator like this:
void ostream::operator << (const char *str) {
// Do fancy stuff with the string
}
So when you use << on cout that function ends up being called, and the r-value is passed to that function.
- Momo-the-Monkey
-
Momo-the-Monkey
- Member since: Oct. 15, 2005
- Offline.
-
- Forum Stats
- Member
- Level 45
- Musician
Somehow I knew that I just didn't make the connection, haha. Thanks for clearing that up Diki.

