Hello,
I'm currently using
char *thisvar = "stringcontenthere";
to declare a string in C.. Is this the best way to declare a string?
Hello,
I'm currently using
char *thisvar = "stringcontenthere";
to declare a string in C.. Is this the best way to declare a string?
Is this C or C++? In C++ you should use std::string
:
std::string aString("stringcontenthere");
in C++, the best is to use std::string:
std::string aString = "stringcontenthere";
If you want to create a C string (and really not C++) you may find entry 6.2 of the C FAQ helpful: http://c-faq.com/aryptr/aryptr2.html
As other suggested, and I you want to "do it" the C++
way, use a std::string
.
If you somehow need a C-string
, std::string
has a method that gives a const char*
.
Here is an example:
#include <iostream>
#include <string>
void dummyFunction(const char* str)
{
// Do something
}
int main(int, char**)
{
std::string str = "hello world!";
dummyFunction(str.c_str());
return EXIT_SUCCESS;
}
In C it depends on how you'll use the string:
char* str = "string";
method is ok (but should be const char*
)char str[] = "string";
char* str = strdup("string");
, and make sure it gets free
d eventually.if this doesnt cover it, try adding more detail to your answer.