Highway62 Highway62 - 1 year ago 56
C Question

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

I have a struct:

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

and a function to convert strings to upper case:

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

and in my main function I assign values to the struct members and want to convert the surname to upper case:

mentry->surname = "bob";
mentry->house_no = 17;
mentry->postcode = "GK116BY";

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

Answer Source

Your toUpper() implementation should work fine. However, you should pay attention to the warnings from your compiler (or turn up the warning levels if you didn't get any -- you should see something when you assigne a string literal to a char * like that). String literals are const, i.e. they cannot be modified. When you try to write to them, this will cause the segmentation fault you are seeing.

You need something like:

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

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

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

And of course, be sure to call free() later, either way.