00:00
00:00
Newgrounds Background Image Theme

1amghost just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

C++ char* s help

729 Views | 3 Replies
New Topic Respond to this Topic

C++ char* s help 2013-03-14 20:38:29


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

Response to C++ char* s help 2013-03-14 20:44:53


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

Response to C++ char* s help 2013-03-14 21:40:55


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.

Response to C++ char* s help 2013-03-15 00:10:38


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