williamgherman / c-solutions

My Solutions to K. N. King's "C Programming: A Modern Approach", second edition
GNU General Public License v3.0
536 stars 211 forks source link

I don't think the answer given in c13 exercise 5 b is correct #117

Open BigWillem opened 1 year ago

BigWillem commented 1 year ago

I could be wrong, but when I tried to compile a program that uses this function, I got the following errors:

13E05.c: In function 'capitalize': 13E05.c:37:21: warning: passing argument 1 of 'isalpha' makes integer from pointer without a cast [-Wint-conversion] if (isalpha(c)) ^ In file included from 13E05.c:4:0: c:\mingw\include\ctype.h:71:38: note: expected 'int' but argument is of type 'char ' _CRTIMP cdecl MINGW_NOTHROW int isalpha(int); ^~~ 13E05.c:38:21: warning: passing argument 1 of 'toupper' makes integer from pointer without a cast [-Wint-conversion] toupper(c); ^ In file included from 13E05.c:4:0: c:\mingw\include\ctype.h:96:38: note: expected 'int' but argument is of type 'char ' _CRTIMP cdecl MINGW_NOTHROW int toupper (int); ^~~

magict4 commented 1 year ago

I also feel the answer is wrong. Here is my proposing solution.

#include <ctype.h>
void capitalize(char *str) {
    char *c = str;
    while (*c != '\0') {
        if (isalpha(*c))
            *c = toupper(*c);
        c++;
    }
}
BigWillem commented 1 year ago

I virtually have the same answer, only without the if statement. I'm not sure, but I think toupper() only does something to characters in the alphabet so the isalpha() call would be redundant.


// using pointer arithemtic 
void capitalize2(char *str)
{
    char *p = str; 
    while(*p != '\0')
    {
        *p =  toupper(*p);
        *p++;
    }
    *p = '\0'; 

    printf("%s", str); 
}