How to convert string (char *) to upper or lower case in C

I have a structure:

typedef struct entry {
char *surname;
int house_no;
char *postcode;
} BEntry;

      

and a function to convert strings to uppercase:

void toUpper(char *str){
    while (*str != '\0')
    {
        *str = toupper(*str);
        str++;
    }
}

      

and in my main function I am assigning values ​​to structure members and want to convert the last name to upper case:

mentry->surname = "bob";
mentry->house_no = 17;
mentry->postcode = "GK116BY";
toUpper(me->surname);

      

What is the correct way to convert a string to uppercase by passing a char pointer to a function like this? My program is returning a segmentation fault. Any help is greatly appreciated, thanks.

+3


source to share


3 answers


Your implementation toUpper()

should work fine. However, you should pay attention to your compiler warnings (or turn on warning levels if you didn't get them), you should see something when you assign a string literal to char *

like this). String literals const

, i.e. They cannot be changed. When you try to write to them, it will cause the segmentation fault you see.

You need something like:

mentry->surname = malloc(4);
strcpy(mentry->surname, "bob");

      



or more convenient, but not part of the standard C path:

mentry->surname = strdup("bob");

      

And of course, be sure to call free()

later anyway.

+3


source


String literals such as "Hello, World!"

cannot be written. Or duplicate the string literal:

hw = strdup("Hello, World!");

      



or declare a variable char[]

and initialize it to a string literal. As a special case, string literals used in this way can be written:

char hw[] = "Hello, World!";

      

+1


source


The easiest way to convert char *

to lower or upper case in c is withstrdup

#include <string.h>

char    *to_uppercase(char *s)
{
    int i = 0;
    char    *str = strdup(s);

    while (str[i])
    {
        if (str[i] >= 97 && str[i] <= 122)
            str[i] -= 32;
        i++;
    }
    return (str);
}

      

+1


source







All Articles