I have written a replacechar function which replaces an instance of a source char with a replacement char. The function works in that the string is changed as expected but when I attempt to use the return value of the function, puts just outputs a blank line.
Can someone please explain what is happening and what I would need to change in replacechar to fix.
#include <stdio.h> /* puts */
#include <string.h> /* strcpy */
#include <stdlib.h> /* malloc, free */
char* replacechar(char* s, char ch1, char ch2) {
while (*s) {
if (*s == ch1)
*s = ch2;
*s++;
}
return s;
}
int main()
{
char* s = malloc(8);
strcpy(s, "aarvark");
puts(replacechar(s, 'a', 'z')); /* prints blank line */
puts(s); /* prints zzrvzrk as expected */
free(s);
return 0;
}
Thanks for all the responses.
I have changed to this (which now works fine).
char* replacechar(char* s, char ch1, char ch2) {
char* p = s;
while (*p) {
if (*p == ch1)
*p = ch2;
p++;
}
return s;
}
It returns the value of the
spointer once it’s been incremented past the end of the string. Make a local variable inreplacechar(), and increment it, and return the original value ofs.