6

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?

DrBowe
  • 115
  • 2
  • 2
  • 6
  • "However, this fails, since all I'm doing is modifying the value of input that is passed in and not the actual memory address." No you *are* passing in a memory address, and modifying the value it points to. The only thing you are doing wrong is providing an address you are not allowed to modify. – Segmented Mar 02 '15 at 01:14
  • *All* parameters in C are passed by value. In this case, the value being passed happens to be a pointer value, the address of the first element of the string literal `"Bad"`. – Keith Thompson Mar 02 '15 at 01:19

1 Answers1

12

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";
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 2
    The second answer has a good visual for this...http://stackoverflow.com/questions/1335786/c-differences-between-char-pointer-and-array – Alex Mar 02 '15 at 01:11
  • Thanks! Wasn't aware there was a difference between `char *test` and `char test[]` but it's good to know now. Appreciate the help – DrBowe Mar 02 '15 at 01:25
  • 2
    There are a lot of differences between `char *test = "Bad";` and `char test[] = "Bad";`, and you need to be aware of at least some of them (the primary one at the moment being that the array can be modified but the string literal can't — another is that if you have your compiler set appropriately fussy, it will tell you when you assign a pointer to string literal to a non-const `char *`). – Jonathan Leffler Mar 02 '15 at 01:40