Function that takes a string and converts it to uppercase letters gives error

Asked

Viewed 89 times

2

My code performs double loop for and no longer executes even what I put after the function call stringToUpper() within the main(), or what I put after the loop for.

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


void stringToUpper(char str[]){
    for(int i = 0; i<strlen(str); i++){
        if(str[i]>=97 && str[i]<=122){
            str[i] = str[i] - 32;
        }
    }
    printf("%s\n", str);
}

int main(){
    stringToUpper("All your BASE are Belong to US!");
    return 0;
}

1 answer

3


This is not possible because you are trying to write to static area of memory. You should create text in a dynamic area and then modify it. Or copy the static area text to a dynamic area. Or not modifying any text yet, which seems to make more sense in this case:

#include <stdio.h>

void stringToUpper(char str[]) {
    for (int i = 0; str[i] != '\0'; i++) printf("%c", str[i] - ((str[i] >= 'a' && str[i] <= 'z') ? 32 : 0));
}

int main(){
    stringToUpper("All your BASE are Belong to US!");
}

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

  • Thank you so much for the feedback, @Maniero. I would also like to know why it stops the code in the middle of the loop for.

  • It’s written in the first sentence of the answer.

Browser other questions tagged

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