So I'm very new to c and I have this function that is supposed to take in a word and output it in lowercase. This is what I have tried so far
char *lowercase(const char *word) {
int length = strlen(word);
char *lower = malloc(sizeof(word));
lower[length] = '\0';
for(int i=0; i < length; i++) {
lower[i] = tolower(word[i]);
}
return lower;
}
This outputs ▒▒▒▒▒* for every word I enter.
malloc(sizeof(word))
is not correct because sizeof(word)
is the same as sizeof(char *)
which gives the size of a single pointer. You need to allocate enough for the string including the NUL terminator. So should be malloc(length+1)
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments