ccharc-stringsstring-literalstolower

Can't convert to Lower/uppercase a char* pointer using a loop in C without toupper


I am trying to make a function toLowerCase(char *string) but I am unable to make it work properly.

This is my code

void toLowerCase(char *string) {
    int i = 0;
    while (*(string+i) != '\0') {
        if (*(string+i) >= 'A' && *(string+i) <= 'Z') {
            *(string+i) = *(string+i) + 32;
        }
        i++;
    }
    printf("%s", string);
}

I am trying to loop through the string that is a char * pointer by accessing each element using *(string + i) and using ASCII to convert to Lowercase.

I am new here, if this was answered before I am sorry, but I am asking because I couldn't find a specific solution to my problem. I've tried what's in this thread: Converting Char * to Uppercase in C but it didn't work for me either.

EDIT: This is how I call my function

int main() {
    toLowerCase("HELLO WORLD");
    return 0;
}

EDIT 2: So, I did this, as showed by PSkocik. And it worked, but I don't know why it works like this. Will the toLowerCase() function work with any char * pointer? even if I don't declare it as char array?

This also fixes the problem that Vlad from Moscow pointed out that I am using a string literal

#define T 100
int main() {
    char string[T] = "HELLO WORLD";
    toLowerCase(&string);
    return 0;
}

EDIT 3: Thank you very much for your help! I wasn't expecting to get help so quickly! I didn't know what a string literal was!

Thank you very much for your time


Solution

  • You may not change string literals. Any attempt to change a string literal results in undefined behavior.

    From the C Standard (6.4.5 String literals)

    7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

    So instead of this call

    toLowerCase("HELLO WORLD");
    

    use at least

    char s[] = "HELLO WORLD";
    
    toLowerCase( s );
    

    Pay attention to that it will be much better when the function will return pointer to the modified string and will not output the string. It is the caller of the function that will decide whether to output the modified string.

    So define the function like

    char * toLowerCase( char *string )
    {
        // ...
        return string;
    }