0

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;
}
Panup Pong
  • 1,871
  • 2
  • 22
  • 44
NouName
  • 87
  • 5
  • 2
    You can't write to string literals reliably; you invoke undefined behaviour when you do so. Change the `main()` to `int main(void) { char str[] = "A"; makeLower(str); return 0; }` for example. You should add a newline to the `printf()`; you should probably print in the `main()` function rather than the (no longer general purpose) utility function. Technically, you should pass an `int` containing either an `unsigned char` or EOF to `tolower()` (normally achieved by `tolower((unsigned char)s[i])`). However, you won't run into a problem with `A`. – Jonathan Leffler Nov 05 '16 at 19:47
  • 1
    Maybe your misunderstanding is already that you try to assign something to `argv[0]`. These are supposed to contain information from your environment, in particular `argv[0]` should be the name of your compiled program. If you just run it without the assignment to `"A"` all should work then fine, the strings that `argv` points to are modifiable. – Jens Gustedt Nov 05 '16 at 19:53

1 Answers1

0

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.

P.P
  • 117,907
  • 20
  • 175
  • 238