LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   casting a const char into a char (https://www.linuxquestions.org/questions/programming-9/casting-a-const-char-into-a-char-518733/)

MicahCarrick 01-12-2007 02:19 PM

casting a const char into a char
 
What happens when you cast a const char* to a char*?

Code:

const char* str1 = "test";
char *str2 = (char*) str1;

Is str2 now a new string? Does it need to be freed?

Guttorm 01-12-2007 03:18 PM

Hi

Short answer: no :)

But I'll try to explain. Strings in C are confusing. It's usually better to think of them as an array of characters.

These lines are equivalent:
Code:

const char *str = "test";
const char str[5] = { 't','e','s','t','\0' };

Code:

char *str2 = (char*) str1;
This makes a new pointer variable called str2 and it points to str1 (the 't' character). If you try to modify that string, you will get a segmentation fault.

To make a new string that's a pointer to heap memory that you can modify and then free, use the strdup function.

Code:

char *str2 = strdup(str1);
The strdup allocates memory for the string with malloc, and then copies the string to that memory, and finally it returns a pointer to the new allocated memory.

MicahCarrick 01-12-2007 03:24 PM

Right. I saw this in some code, and I can't figure out why the author wanted to cast out the const'ness of the string

xhi 01-12-2007 07:26 PM

Quote:

Originally Posted by MicahCarrick
Right. I saw this in some code, and I can't figure out why the author wanted to cast out the const'ness of the string

well it would make sense if the string in question is not a literal.


All times are GMT -5. The time now is 10:02 AM.