Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a char array inside a function in C [duplicate]

Tags:

arrays

c

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?

like image 769
DrBowe Avatar asked Mar 02 '15 00:03

DrBowe


1 Answers

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?

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";
like image 138
R Sahu Avatar answered Nov 10 '22 09:11

R Sahu