Be a Supporter!

C++ char* s help

  • 328 Views
  • 3 Replies
New Topic Respond to this Topic
Momo-the-Monkey
Momo-the-Monkey
  • Member since: Oct. 15, 2005
  • Offline.
Forum Stats
Member
Level 45
Musician
C++ char* s help 2013-03-14 20:38:29 Reply

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.


Hello, from the past!
[ PHP: Main ]

BBS Signature
Momo-the-Monkey
Momo-the-Monkey
  • Member since: Oct. 15, 2005
  • Offline.
Forum Stats
Member
Level 45
Musician
Response to C++ char* s help 2013-03-14 20:44:53 Reply

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 *.


Hello, from the past!
[ PHP: Main ]

BBS Signature
Diki
Diki
  • Member since: Jan. 31, 2004
  • Offline.
Forum Stats
Moderator
Level 13
Programmer
Response to C++ char* s help 2013-03-14 21:40:55 Reply

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
Response to C++ char* s help 2013-03-15 00:10:38 Reply

Somehow I knew that I just didn't make the connection, haha. Thanks for clearing that up Diki.


Hello, from the past!
[ PHP: Main ]

BBS Signature