How to create a function that changes characters of a string?

Viewed 38

I'm new to coding and I've been studying C recently. Basically, I wanted to create the following function, which modifies every string element:

char *stralt(char *s, char ch)
{
    int i;
    for (i=0; i!='\0'; i++)
        s[i] = ch;
    return s;
}

And when I try to use it on int main(), like this:

int main()

{
    printf("%s", stralt("test",'x'));   
}

The prompt shows "test" instead of "xxxx". What is wrong with this code and how could it work properly? Thanks!

1 Answers

You have two problems, one of which isn't apparent because the other doesn't allow it to occur.


You have:

for (i = 0; i != '\0'; i++)

Here, you compare the value of i against '\0', which is 0. Since i is 0 at the beginning of the for loop, the condition i != '\0' will be false, and the loop will exit before entering the body.

It seems that you meant to say:

for (i = 0; s[i] != '\0'; i++)

The other problem is that you're trying to modify a string literal. s[i] = ch; is invalid if s points to a string literal, as it does in your example.

Instead, you have to have a modifiable array of characters. This could be accomplished by modifying your main like:

int main()
{
    char test_str[] = "test";
    printf("%s", stralt(test_str, 'x'));   
}
Related