0

When i run the code i got no output and program crash Anyone know how to correctly print out the char pointer ?

#include <stdio.h>
char *toUpperCase(char *str)
{
    int i = 0;
    while(str[i] != '\0')
    {
        str[i] = str[i] - 32;
        i++;
    }
    return str;
}

int main()
{
     printf("%s", toUpperCase("hello"));
     return 0;
}
emperor_c
  • 99
  • 2
  • 9
  • You can't write to string literals. They are read-only, so that is undefined behavior. – mediocrevegetable1 May 26 '21 at 13:53
  • Also, consider avoiding the use of magic numbers to make your intent more clear. And that `while` loop would look better as a `for` loop. Also, this function doesn't work properly when there are non-alphabet characters: https://godbolt.org/z/YaYnzn99M – mediocrevegetable1 May 26 '21 at 13:58

1 Answers1

1

Modifying string literals is prohibited and trying to do so invokes undefined behavior. You have to pass a pointer to modifiable buffer instead.

#include <stdio.h>
char *toUpperCase(char *str)
{
    int i = 0;
    while(str[i] != '\0')
    {
        str[i] = str[i] - 32;
        i++;
    }
    return str;
}

int main()
{
     char str[] = "hello";
     printf("%s", toUpperCase(str));
     return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70