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?
Asked
Active
Viewed 80 times
-6
-
3Why do you say you can't do `*str = 'X'`? – psmears Feb 16 '16 at 22:01
-
The code that calls the function should ensure to pass a mutable buffer – M.M Feb 16 '16 at 22:04
-
You might find http://stackoverflow.com/questions/2229498/passing-by-reference-in-c helpful. – stonemetal Feb 16 '16 at 22:04
-
If it took `char cons* str`, you wouldn't be able to. But since it takes `char* str`, you can. Try it out. – Petr Skocik Feb 16 '16 at 22:05
-
Show your code instead of describing it. – Jabberwocky Feb 16 '16 at 22:40
1 Answers
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