I have the following example, taken from here:
// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
int main ()
{
std::string str ("Please split this sentence into tokens");
char * cstr = new char [str.length()+1];
std::strcpy (cstr, str.c_str());
// cstr now contains a c-string copy of str
char * p = std::strtok (cstr," ");
while (p!=0)
{
std::cout << p << '\n';
p = strtok(NULL," ");
}
delete[] cstr;
return 0;
}
As far as I understand str
is a string, str.c_str()
is a pointer pointing to the first element of an array that contains characters of str
as its elements. Then using std::strcpy
we take the value of the address given as its second argument and assign this value to the pointer that is given as the first argument (cstr
).
However, I have the following example, taken from here:
#include <iostream>
#include <cstring>
int main()
{
char *str = new char[100];
std::strcpy(str, "I am string!");
std::cout << str;
delete[] str;
}
And now as the second argument we have a string (and not a pointer to array as it was in the first example).
Can anybody, please, clarify this inconsistency?