简体   繁体   中英

error convert character in string to uppercase

I'm trying to convert character of a string to uppercase letters

int main (void)
{
    int i = 0;
    int n = 0;
    static char *str[] = { "wow",
                           "RACEcar", 
                           "No devil lived on.",
                           "rotor" };

    for(i = 0; i < strlen(*str); i++)
    {
        if(str[i] != NULL)
        {
            n = function(str[i]);
        }
    }
    return 0;
}

int function(char* x)
{
   int i = 0;
   int j = strlen(x);
   char c;
   for(i = 0; i < j; i++)
   {
      c = toupper(x[i]);
      x[i] = c;
   }

   return 0;
}

I got an error saying exc bad access, code 2 at line where x[i] = c; I'm not sure why I get this error, do I need to create another string and assign c to the new string? toupper return the uppercase version of the character but didnt actually change the element itself, so I'm not sure what wrong with assigning the value return by toupper back to the element.

Your code attempts to modify a string literal , which causes undefined behaviour.

The string "No devil lived on." is non-modifiable . To help the compiler catch the error you should declare the array as:

static char const *str[] = { "wow", // etc.

For historical reasons, the compiler has to let it pass without breaking compilation if you forget to include the const . But it is still an error nonetheless, and some compilers will warn anyway.

For gcc you can use the flag -Wwrite-strings to disable support for the historical case; this will cause an error message to be generated for your code as-is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM