-6

I have a function which take a char *str and const char a as parameters and change every single a in *str to 'X'. Since I can't modify the value pointer point to like *str = 'X'. How I am going to do this problem?

indiv
  • 17,306
  • 6
  • 61
  • 82
Kevin Wei
  • 11
  • 2

1 Answers1

0

Let's suppose we have a function like this:

int change_char( char *str, const char a, const char b) {
    int n = 0;
    if ( str ) {
        while ( *str ) {
            if ( *str == a ) {
                *str = b; // Can I modify the value pointed by the pointer?
                ++n;
            }
        ++str;  // Can I modify the pointer?
        }
    }
    return n;
}

When we call that function, like in the following sample, the pointer is passed by value, so you can't modify the original pointer (only its local copy), but you can modify the value of the object pointed by that pointer:

char test[] = "Hello world!";
change_char(test, 'o', 'X');
printf("%s\n",test);   // it will output HellX wXrld!
Bob__
  • 12,361
  • 3
  • 28
  • 42
  • I used char * tset = "Hello world" in the original test. As a result I always get the same string every time I run it. Could you explain more specific about the difference? Thank you! – Kevin Wei Feb 16 '16 at 23:04
  • @KevinWei `"Hello world"` is a const string literal, you can use it to initialize a null terminated string with `char test[] = "Hello world!";` and then modify the character in it, but if you declare a pointer like `char *test = "Hello world"` it will point to a costant and any attempt to modify the chars will result in a run time error. In that case you should allocate memory and then copy the string. See a live example [here](https://ideone.com/0dlUAJ). – Bob__ Feb 17 '16 at 00:01