Having this:
#include
#include
#include
char *up(char *);
int main() {
char initstr[20];
printf(\"ente
The bug in up
is you increment ret
all the way to the newline (\n
) and return ret
pointing to this character in the string. You should instead return a pointer to the initial character.
for
clauses with an empty body is hard to read and error prone.toupper()
.char
values to toupper()
because this function and all functions from
is only defined for values of type unsigned char
and the special negative value EOF
. On platforms where char
is signed by default, the string might contain negative char
values which may cause undefined behavior when passed to toupper()
. Cast these as (unsigned char)
to avoid this issue.Here is a modified version:
#include
#include
char *up(char *s) {
for (size_t i = 0; s[i] != '\0'; i++) {
s[i] = toupper((unsigned char)s[i]);
}
return s;
}
int main() {
char initstr[20];
printf("enter string\n");
if (fgets(initstr, sizeof initstr, stdin)) {
char *str = up(initstr);
printf("%s\n", str);
}
return 0;
}