On Mar 18, 2009, at 9:33 PM, Alvin ONeal wrote:

> Can someone please tell me what the best practice / correct way of  
> doing this is? I want the error I'm getting to go away.
>
> char* myCString = "My C string";

Specifying a string literal in C/C++ is ALWAYS a "const char *".  That  
is why you are getting the warning.

>
> I think I've used one of these before to avoid the message... but it  
> just seems a cludgy way to do things.
> // This
> char * myCString = string("My C string").c_str()

Calling "c_str" on a std::string also returns a "const char *", not a  
"char *".

>
> // Or this
> char * myCString;
> strcpy(myCString, "My C string");

This would crash (or do other bad things to your stack and/or heap)  
unless you write:

char *myCString = new char[50];
strcpy(myCString, "My C string");

because a pointer has no memory associated with it (except the memory  
to store the address to the actual data) until you create it using  
either "malloc" or "new".

You only really need to do any of these things if you are planning on  
modifying the contents of the string.  If you are just going to be  
printing it, or passing it to functions that expect a "const char *"  
and such, then you can just use a "const char *".  Using std::string  
is usually a good choice for many things (in my opinion) because of  
the useful methods and abstractions it offers (iterators, searching,  
appending, etc).   If you are using standard C library functions  
(string modifications, reading from files, etc), you need to use a  
properly allocated "char *".

Clear as mud?

Grant

--------------------
BYU Unix Users Group 
http://uug.byu.edu/ 

The opinions expressed in this message are the responsibility of their
author.  They are not endorsed by BYU, the BYU CS Department or BYU-UUG. 
___________________________________________________________________
List Info (unsubscribe here): http://uug.byu.edu/mailman/listinfo/uug-list

Reply via email to