0

Can a char* in C++ receive a string as a parameter? If so how does this work.

Example:

myfunc("hello"); //call
myfunc(char * c)
{ ...
}

How exactly are chars related to strings?

Cloud
  • 18,753
  • 15
  • 79
  • 153
Sal Rosa
  • 551
  • 2
  • 8
  • 12

2 Answers2

2

The type of the literal "hello" is const char[6], that is an array of characters with space for the string and a null terminating byte.

C++ allows for converting a function argument to another type when passing it. In this case the array type gets converted to pointer type, const char *, with the pointer referencing the first character with value 'h'.

C++03 allowed for conversion to char *, dropping the const, but it was undefined behavior to actually modify the string. This was done for old-school C compatibility and has been revoked in the new C++11 standard, so your example will not pass a newer compiler.

Incidentally, due to legacy considerations inherited from C, it would make no difference if the function were instead declared as myfunc(char c[6]). The type of c would still be char *.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
-1

It wont work as expected in your example. Using strings this way (a pointer to the beginning char) only works if the string is null terminated. This is how the old c_str works. If we have a reference to the first char, we can iterate until we find the terminating character, "\0" to access the entire string.

Ben Anstey
  • 21
  • 4
  • 1
    What does null termination have to do with the *first* character, where is there a non-null terminated string in the example, and what does a newline have to do with anything? – Potatoswatter Feb 07 '13 at 00:00
  • what does *"\n" to access the entire string* mean? if it's null terminated, shouldn't you iterate until you find the null? seems the example should work just fine unless myfunc does something funcy (:p) with the parameter. – thang Feb 07 '13 at 00:08
  • i meant to type \0 as the terminating char – Ben Anstey Feb 07 '13 at 03:46
  • What does it have to do with the first char? The string is stored in contiguous blocks, so all you need is a pointer to the first char, and to make sure the string is terminated. – Ben Anstey Feb 07 '13 at 03:49
  • just read dogbert's post for a better explanation. – Ben Anstey Feb 07 '13 at 03:51