0

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;
}
Obscuritas
  • 59
  • 6
  • 3
    You should be very careful with this. The `Hello` string you provide here is not a char-array, it is a `char *` and doing such things with `char *` is not specified by standard and leads to undefined behaviour. – CuriousPan Jan 27 '23 at 14:42
  • @CuriousPan so Im fairly new to c. What would I change to meet these standards? – Obscuritas Jan 27 '23 at 14:43
  • To fix it, declare in main: `char s[] = "Hello";`. Then you can `replaceCharWithChar(s, 'H', 'T')`. The declaration of the `s` variable gets you a local array, initialized to your string, that you can modify all you want. – Dúthomhas Jan 27 '23 at 14:43
  • 2
    Also, your function should return a `char*` not a `char`; save a copy of the passed `string` argument (before you start changing it) and return that (without the star). – Adrian Mole Jan 27 '23 at 14:44
  • I would suggest reading this post: https://stackoverflow.com/questions/25653034/the-difference-between-char-and-char – CuriousPan Jan 27 '23 at 14:46
  • 1
    What would be the value of `return *string;` after a loop with `while(*string != '\0')`? – mch Jan 27 '23 at 14:46
  • Obscuritas The **biggest** mistake is not enabling all compiler warnings. A good well enabled compiler would complain about `printf("%s:", replaceCharWithChar("Hello", 'H', 'T');` and save you time. – chux - Reinstate Monica Jan 27 '23 at 21:27

1 Answers1

0

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;
}
Elzaidir
  • 891
  • 6
  • 13