Monil Monil - 2 months ago 9
C Question

C: How can I edit a C-string in a function without using malloc

I have a

string
in
main
and I would like to pass the address of that string to a function that will edit the contents of that string. I do not want to use malloc.

My code currently looks like this:

int main(){
char* str = "Hello";
char* para1[] = {"Tea", "Coffee"};

printf("str: %s\n para1: %s\n", str, para1[0]);

my_func(str, &para1);

printf("str: %s\n para1: %s\n", str, para1[0]);

return 1;
}

int my_func(char* str, char** para1){
printf("str: %s\n", str);
str[0] = 'W';
para1[0] = "Popcorn";

return 1;
}


I don't understand how I can change the first letter of the string from
H
to
W


Could you explain what I am doing wrong?

Answer

String literals are read-only. When you define:

char* string_literal = "Hello";

You're getting a pointer to the text "Hello" that resides in read-only memory.

If you declare this as a char array:

char string[] = "Hello";

Then you can modify the contents of string with array index notation:

string[0] = "W";

Now, you can replace a pointer to a string literal with a pointer to another string literal. For example,

string_literal = "New string literal";

because here what you're actually doing is reassigning the pointer called "string_literal" to point to another address in memory. The pointer itself is writeable, but the memory to which it points is read-only. This is why your assignment to para1 succeeds.