Home > other >  Wrong output from tolower function
Wrong output from tolower function

Time:01-27

I have a problem with tolower function. Tried to use it with argv but output was $0@. What's wrong with my code?

#include <stdlib.h>
#include <stdio.h>

void makeLower(char *s) {
    int i;
    for(i = 0; s[i] != '\0'; i  ){
        s[i] = tolower(s[i]);
        }
        printf("%s", s);
}

int main(int argc, char *argv[]) {
    argv[0]="A";

    makeLower(argv);
    return 0;
}

CodePudding user response:

argv is a pointer to pointer, which is a char**. But the function takes a char*. So, you need to pass like:

makeLower(argv[0]);

But this isn't going to work because the argv[0] now points to a string literal. Modifying a string literal is undefined.

Instead pass a modifiable array like:

int main(int argc, char *argv[]) {
    char arr[] = "A";

    makeLower(arr);
    return 0;
}

Other option is to make a copy of the string literal passed (via argv[0]) and then you will be able to modify it. Basically, the idea is that you can't legally modify string literals in C.

  • Related