Is there anything bad about the following code? Although it runs fine, but should I have allocated a memory to the character pointer first before initializing it?
const char *a;
string b;
getline(cin, b) ;
a=&b[0u];
Is there anything bad about the following code? Although it runs fine, but should I have allocated a memory to the character pointer first before initializing it?
const char *a;
string b;
getline(cin, b) ;
a=&b[0u];
It is fine since C++11.
Before C++11, there was no formal guarantee that operator[]
would return a reference to a character that would be part of a null-terminated character array (i.e. a C-style string). One consequence of that missing guarantee was that &b[0u]
would have been undefined behaviour if b
was an empty non-const
string.
(Actual implementations typically behaved correctly anyway, because that's the only sane way of implementing std::string
, but that's another story.)
See also http://en.cppreference.com/w/cpp/string/basic_string/operator_at:
reference operator[]( size_type pos );
(...)
If
pos == size()
, a reference to the character with valueCharT()
(the null character) is returned.(since C++11)
Still, the code you've posted is not particularly good style. Why create a pointer with an uninitialised value and then assign it a value later on, and why bother with the more complicated syntax?
Here's an improved version of the code:
std::string b;
std::getline(std::cin, b);
auto const a = b.c_str();
In this version, a
is const
, so you cannot accidentally make it point to something else; you also make the compiler deduce the type (char const*
) automatically. And c_str()
is a clearer way of saying what your code actually means.
As suggested by @goodvibration you should use c_str
-> Reason: If you're using a compiler that doesn't support C++11 and higher versions of the standard, the std::string
object won't include an appropriate null termination, which signals the end of the string when working with c-like methods. c_str
takes care about the correct "format". See this stackoverflow link for additional information.
Hope that helps.
Simply use the string::c_str() method to get the const char *
string strText = "My String";
const char * chText = strText.c_str ();
There are two methods for this
You can use anyone based on taste, readability, etc.
std::string s;
std::getline(std::cin, s);
const char * a = s.c_str();