I have a function that tries to make all the letters in a word lowercase, if needed. I debugged my program and found out I was getting my segfault from this function. Both word and lowerword are strings.
Here is the call:
lowerword = word_to_lower(word);
Here is the function itself:
char * word_to_lower(char * word) {
int i;
char * lowerword;
for (i = 0; i < strlen(word); ++i) {
lowerword = (char *) tolower(word[i]);
printf("%s\n", lowerword);
}
return lowerword;
}
I am very new to C so a detailed explanation would be greatly appreciated 🙂
You are trying to cast a
charinchar*which are two different things. The first is a value (a character), the second is a pointer (a variable which points to a location in the memory at which there is a character stored). If you want to return a completely processed string, you should first allocate an array of char of the sizestrlen(word), and then setting its elements (i.e. each character) to the proper value with the call totoLower.In the end, you should have something like
Be sure you understand the concepts behind “pointers” and “arrays” in C, and the processes of allocating and freeing memory. It seems by the way you use them that you’re not comfortable with these.
EDIT : As remarked in the comments, this function should take a
const char *as a parameter.