tags:

views:

216

answers:

6

Hello,

I'm currently using

char *thisvar = "stringcontenthere";

to declare a string in C.. Is this the best way to declare a string?

+1  A: 

Is this C or C++? In C++ you should use std::string:

std::string aString("stringcontenthere");
Péter Török
+1  A: 

in C++, the best is to use std::string:

std::string aString = "stringcontenthere";
sinec
+4  A: 

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

Jens
+1 for providing the C FAQ link
lz_prgmr
Thanks, i'll surly look at it!
Daniel
A: 
const char *thisvar="stringcontenthere";
KMan
It must read thisvar = "stringcontenthere" and it should be const char*
frast
@Frast: just missed it! thanks for the poke.
KMan
+2  A: 

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;
}
ereOn
+6  A: 

In C it depends on how you'll use the string:

  • named constant: your char* str = "string"; method is ok (but should be const char*)
  • data to be passed to subfunction, but will not not used after the calling function returns:
    char str[] = "string";
  • data that will be used after the function it is declared in exits: char* str = strdup("string");, and make sure it gets freed eventually.

if this doesnt cover it, try adding more detail to your answer.

David X