I have to capitalize the first letter of every word (words are separated by a space) into a given array of char. I wrote the code but I can't figure out why it's not working nor displaying anything in output.
Here's the code:
void LetterCapitalize(char *str) {
char *str2;
int i = 0;
str2[i] = toupper(str[0]);
i++;
while (str[i]) {
if (str[i] == ' ') {
str2[i] = str[i];
str2[i + 1] = toupper(str[i] + 1);
i += 2;
} else {
str2[i] = str[i];
i++;
}
}
printf ("%s", str2);
}
And here's the main:
int main(void) {
char stringa[16] = "some string here";
LetterCapitalize(stringa);
return 0;
}
There are multiple problems:
mainis not null terminated because the initializer has exactly 16 characters, the defined length of the array, so there is no space for the null terminator. It is safer to omit the array length and let the compiler compute it from the initializer, including the null terminator:str2is uninitialized: storing characters to it has undefined behavior. You could instead either modify the argument string in place or allocate a copy and modify that.the logic in
LetterCapitalizeis risky: you assume that words are separated by a single space and that the string does not end with a space.the
charargument totoupper()should be cast as(unsigned char)to avoid undefined behavior on negativecharvalues on platforms where the typecharis signed by default.Here is a modified version: