Hello guys!
I have a little questions here... I wrote this strtouppercase function which return a pointer to char but I would like to know if there is a shorter version with pointer notation or if it could be improved in any ways:
the function doesn't return the correct string. Why is it? I think I might have some missunderstanding on pointer notation or I'm a bit confused with pointers.
Thank you very much in advance!
P.S: BTW this is plain C not C++ but I hope you can help please :P
The second one was the issue, could you please elaborate why isn't it recommended to use the second? And how could I go about writing it with (*p)++? Thank you! And thanks for the EDIT! :)
this (*p)++ increases the content of p (pafter == pbefore but the content (*p) will be e.g. 'A' -> 'B')
this *(p++) increases the pointer and returns the content (pafter == pbefore + 1)
Modifying a variable during an assignment isn't recommended because well, you experienced it yourself: it's to hard to predict what's the result.
It's perfectly predictable what the result is. *p++ makes p point to the next character, so it shouldn't come as a shock that the loop body handles the wrong character.
No, those two variants just show the difference between pre-increment and post-increment (i.e. *++p and *p++).
If you know the difference, the code is rather obvious.
Edit: Still, I'm not advocating this over the first variant with separate increment, as that one is more readable.
And the for variant is still better. Oh, and str[i]!='\0'
For your code above it would be wise to have the user provide a char* out variable, if only to make it explicit that memory is being allocated and must be freed afterward.
Here is another example, rather than allocating memory for another string I am modifying the original. This has its own cavets and I wouldn't recommend using any of these examples for anything other than learning.