So I've been playing around with C lately and have been trying to understand the intricacies of passing by value/reference and the ability to manipulate a passed-in variable inside a function. I've hit a road block, however, with the following:
void modifyCharArray(char *input)
{
//change input[0] to 'D'
input[0] = 'D';
}
int main()
{
char *test = "Bad";
modifyCharArray(test);
printf("Bad --> %s\n", test);
}
So the idea was to just modify a char array inside a function, and then print out said array after the modification completed. However, this fails, since all I'm doing is modifying the value of input
that is passed in and not the actual memory address.
In short, is there any way I can take in a char *input
into a function and modify its original memory address without using something like memcpy
from string.h?
In short, is there any way I can take in a
char *input
into a function and modify its original memory address without using something likememcpy
from string.h?
Yes, you can. Your function modifyCharArray
is doing the right thing. What you are seeing is caused by that fact that
char *test = "Bad";
creates "Bad"
in read only memory of the program and test
points to that memory. Changing it is cause for undefined behavior.
If you want to create a modifiable string, use:
char test[] = "Bad";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With