I want to search my char-array for a certain char and replace it with another one. By executing the following code I get this error:
Process finished with exit code 138 (interrupted by signal 10: SIGBUS)
#include <stdio.h>
char replaceCharWithChar(char *string, char toReplace, char replacement) {
while(*string != '\0') {
if(*string == toReplace) {
*string = replacement;
}
string ;
}
return *string;
}
int main() {
printf("%s:", replaceCharWithChar("Hello", 'H', 'T');
return 0;
}
CodePudding user response:
There are multiple errors. First replaceCharWithChar
returns a char
, but your printf string expects a char*
. Also, you are modifiying a pointer to a string literal which is undefined behaviour.
To fix your issue, fix the type error and return the original string pointer (or nothing, or the number of character replaced). And don't use a string literal, use a char array instead:
#include <stdio.h>
char replaceCharWithChar(char *string, char toReplace, char replacement) {
char* string_beginning = string; //Store the pointer to the beginning of the string
while(*string != '\0') {
if(*string == toReplace) {
*string = replacement;
}
string ;
}
return string_beginning;
}
int main() {
char string[] = "Hello";
printf("%s:", replaceCharWithChar(string, 'H', 'T');
return 0;
}