How to convert string to char * in C++?

c++, visual-c++

Solution

`strcpy` doesn't allocate memory for you, you must do it yourself, remembering to leave space for the null termination character:

char* url = new char[sup.length()+1];

or

char url[sup.length()+1];
//...
strcpy(url, sup.c_str());

In the first case, don't forget to `delete[]` the array. The second case will only work if your compiler supports C99 variable-length arrays as an extension.

Problem

How can I convert a `string` in to `char *` I was using the following method, but it doesn't work. At runtime it gives me the following error: Run-Time Check Failure #3 - The variable 'url' is being used without being initialized. eventhough I have initialized it as shown in the code bellow. Can you please show me with an example? ``` char* url; sup = "news" sup="http://www."+sup+"yahoo.com"; strcpy(url, sup.c_str()); ``` I am using Microsoft Visual Studio 2010, C++ in console

Original source