I have just started learning pointers, and after much adding and removing *s my code for converting an entered string to uppercase finally works..
#include <stdio.h>
char* upper(char *word);
int main()
{
char word[100];
printf("Enter a string: ");
gets(word);
printf("\nThe uppercase equivalent is: %s\n",upper(word));
return 0;
}
char* upper(char *word)
{
int i;
for (i=0;i<strlen(word);i++) word[i]=(word[i]>96&&word[i]<123)?word[i]-32:word[i];
return word;
}
My question is, while calling the function I sent word which is a pointer itself, so in char* upper(char *word) why do I need to use *word?
Is it a pointer to a pointer? Also, is there a char* there because it returns a pointer to a character/string right?
Please clarify me regarding how this works.
That’s because the type you need here simply is “pointer to char”, which is denoted as
char *, the asterisk (*) is part of the type specification of the parameter. It’s not a “pointer to pointer to char”, that would be written aschar **Some additional remarks:
It seems you’re confusing the dereference operator
*(used to access the place where a pointer points to) with the asterisk as a pointer sign in type specifcations; you’re not using a dereference operator anywhere in your code; you’re only using the asterisk as part of the type specification! See these examples: to declare variable as a pointer to char, you’d write:To assign a value to the space where
ais pointing to (by using the dereference operator), you’d write:An array (of char) is not exactly equal to a pointer (to char) (see also the question here). However, in most cases, an array (of char) can be converted to a (char) pointer.
Your function actually changes the outer char array (and passes back a pointer to it); not only will the uppercase of what was entered be printed by printf, but also the variable
wordof themainfunction will be modified so that it holds the uppercase of the entered word. Take good care the such a side-effect is actually what you want. If you don’t want the function to be able to modify the outside variable, you could writechar* upper(char const *word)– but then you’d have to change your function definition as well, so that it doesn’t directly modify thewordvariable, otherwise the Compiler will complain.