Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create a C String

Tags:

c++

c

string

I'm currently using

char *thisvar = "stringcontenthere";

to declare a string in C.

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

And how about generating a C-String from C++-Strings?

like image 757
Daniel Avatar asked Jun 14 '10 09:06

Daniel


1 Answers

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

  • named constant: your char* str = "string"; method is ok (but should be char const*)
  • 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.

like image 54
David X Avatar answered Nov 03 '22 00:11

David X