Why does this seemingly simple implementation of "strupr" not work?

Asked

Viewed 234 times

0

Error implementation in GCC:

    char* strupr( char *str )
    {
    while(*str) {
        *str++ = toupper(*str);
        }
    }

Note that str is used twice in the assignment.

  • Did the answer solve your problem? Do you think you can accept it? If you don’t know how you do it, check out [tour]. This would help a lot to indicate that the solution was useful to you and to give an indication that there was a satisfactory solution. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

3

There are 2 problems: adding the pointer there will generate an undefined behavior and is not returning anything, have to change the function signature or return something. That’s how it works:

#include <stdio.h>
#include <ctype.h>

void strupr(char *str) {
    while (*str) {
        *str = toupper(*str);
        str++;
    }
}
    
int main(void) {
    char texto[] = "teste";
    strupr(texto);
    printf("%s", texto);
    return 0;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.