-4
void test(char *str2) {
    *str2 = "bbbb";
}

int main(void) {
    char *str1="aaaa";
    test(str1);
    return EXIT_SUCCESS;
}

str1* and str2* point to the same address why I can not change the value of str1 inside the test function? thanks all

albttx
  • 3,444
  • 4
  • 23
  • 42
  • 1
    Trying to modify string literals will invoke *undefined behavior*. – MikeCAT Jun 09 '16 at 07:45
  • Using functions that are not declared or defined *before* is not good. – MikeCAT Jun 09 '16 at 07:45
  • how do you know it didn't? did you print it out? where is the rest of the code then? seems like you knew the answer before writing the code – MoonBun Jun 09 '16 at 07:50
  • pass by reference instead of passing by value. like @MikeCAT shows below. – Shark Jun 09 '16 at 07:52
  • Also see [Why do I get a segmentation fault when writing to a string initialized with char *s but not char s`[]`?](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha). – Lundin Jun 09 '16 at 07:53
  • In any case `*str2 = "bbbb";` does not copy a string. You have to use `strcpy(str2, "bbbb");` (if the destination is legal). – Weather Vane Jun 09 '16 at 08:05

1 Answers1

0

You cannot modify value of str1 because test() won't know where str1 is. To have callee modify caller's local variables, pass pointers to what should be modified.

void test(char **str2){*str2 = "bbbb";}
int main(void) {char *str1="aaaa";test(&str1);return EXIT_SUCCESS;}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • why its pass by value? if i add this prints i get the same address int main(void) { char *str1="aaaa";printf("%p\n",str1);test(str1);return EXIT_SUCCESS;}void test(char *str2) {printf("%p\n",str2);*str2 = "bbbb";} – user1703186 Jun 09 '16 at 11:28
  • @user1703186 Because what is printed in `test` is the address passed from `main` and then printed in `main`... – MikeCAT Jun 09 '16 at 12:08