The C Language specification says that the name of an array is a pointer to the first element of that array.
So this line:
char* ptr = str;
Copies a address from one pointer to another. It also means that these two are equivalent:
char c = *ptr;
char c = ptr[0];
Because a pointer can be treated as an array!
Additionally, because C doesn't have any concept of boolean values
true
or
false
, it treats any non-zero value as
true
and any zero value as
false
. Which means that this line:
while (*ptr != '\0') {
can be simplified to this:
while (*ptr) {
And do yourself a couple of favours: pick an indentation style and stick to it - be consistent! You have mixed two styles in that code:
int main()
{
...
while (*ptr != '\0') {
...
}
return 0;
}
Which while it is readable in a tiny fragment of code like this rapidly becomes unwieldy as your code gets bigger. Get into good habits early, and you won't have so many problems later!
Then stop commenting what code does: comment why it does it! All of your comments say what a line of code does:
char* ptr = str;
while (*ptr != '\0') {
ptr++;
What do they add to the application? How do they help anyone understand what it does? Use comments that help, not that describe code - because if nothing else, they will get "left behind" when you change the code and will contradict what the app is actually doing! So if you trust the comments, you'll believe the code does
this
and wonder why it actually did
that
!
And use sensible names for variables:
str
is just about OK, but
ptr
tells me nothing: what is it a pointer to? What is it used for? Pick a name that reflects usage, not one that is easy to type:
tempStr
perhaps - it's temporarily being used to navigate through
str
after all!
Again, this is less important in a tiny fragment of code, but as it gets bigger and more complex, it becomes much more important!