0

I want to pass a cstring to a function and have it overwritten.

#include <stdio.h>

void changeStr(char* str1)
{
    str1 = "foo";
}

int main()
{
    char* aStr = "abc123";
    printf("%s\n", aStr);
    changeStr(aStr);
    printf("%s\n", aStr);//aStr is still the same :(
    return 0;
}

I tried putting a & in front of the aStr and * in front of str1 but then the program crashes. Why doesn't this work? Isn't the following the same reasoning as here?

Community
  • 1
  • 1
Celeritas
  • 14,489
  • 36
  • 113
  • 194
  • Do you realliy want to change what the pointer is pointing to? Or set the value of a char buffer in a function? – n0741337 Nov 01 '13 at 22:33
  • Set the value of char buffer in function **so that the variable in the calling function has it's value changed as well** – Celeritas Nov 01 '13 at 22:34
  • Then you want a char buffer like `char aStr[20] = "abc123";` ( or malloc'd ) and use something like strncpy() or snprintf() in the function instead of trying to assign the pointer directly. – n0741337 Nov 01 '13 at 22:36

2 Answers2

2

You can do it this way:

#include <stdio.h>

void changeStr(const char** str1)
{
    *str1 = "foo";
}

int main()
{
    const char* aStr = "abc123";
    printf("%s\n", aStr);
    changeStr(&aStr);
    printf("%s\n", aStr);//aStr is still the same :(
    return 0;
}

here :

void changeStr(char* str1) {
    str1 = "foo";
}

str1 is a copy value that holds the address of "abc123", so any changes on it, it will be on the scope of the function. What you need is to modify the value of pointer itself, the holder of the address, so it points to "foo", that's why you need to pass char **, pointer to pointer.

2

You need to use a pointer to pointer:

void changeStr(char** str1)
{
    *str1 = "foo";
}

int main()
{
    ...
    changeStr(&aStr);
    ...
}

In your original version the pointer is passed by value. When you change it to point to a different string, the change does not propagate back to the caller.

NPE
  • 486,780
  • 108
  • 951
  • 1,012