Reputation: 733
I'm converting a C prog that parses a text string and produces human readable o/p.
Got it nearly done, but having a problem understanding the difference in
*char_ptr++
and
char_ptr--
in
token[i++] = c = toupper(*char_ptr++);
if (c == '\0')
{
char_ptr--;
return( 0 );
}
Am I correct in thinking that *char_ptr++
will effectivley point to the next char in the 'string'?
If so, what does char_ptr--
do?
Thanks.
Upvotes: 2
Views: 223
Reputation: 11162
Because you're converting to java, you're going to have to remove the pointers, Java doesn't support them.
token[i++] = c = toupper(*char_ptr++);
if (c == '\0')
{
char_ptr--;
return( 0 );
}
Likely had some sort of declaration above it saying:
char* char_ptr = some_array;
Instead, that'll be
int pos = 0;
And the above code becomes:
token[i++] = c = toupper(some_array[pos++]);
if (c == '\0')
{
pos--;
return( 0 );
}
Upvotes: 1
Reputation: 43508
Regard *char_ptr++
as:
char tmp = *char_ptr;
char_ptr++;
c = toupper(tmp);
So it effectively fetches the current character, and advances the pointer by one. Because the ++
operator has a higher precedence than the unary *
, such an expression is evaluated in the order *(char_ptr++)
.
The incrementation is applied first, but since the postfix ++
operator returns the result prior to the manipulation, the *
dereferencing operator is applied on the old address.
char_ptr--
simply decreases the pointer by one.
Upvotes: 3
Reputation: 5666
This question is solved by precedence rules. The expression
*char_ptr++
is resolved to
*(char_ptr++)
meaning "The character after the character that ptr is pointing to". So when c equals a '\0' (zero), the pointer gets decremented, so it points to the previous character. It practically decrements to the previous character whenever there's a 0 encountered, so that char_ptr points to whatever it pointed to during the last run of the block.
Upvotes: 0
Reputation: 5751
Yes, you are correct. It's a way of "peeking" ahead into the "string" and then returning to where you were if the string was at it's end.
Upvotes: 0
Reputation: 2061
In the same way as ++
increments the pointer and points to the next character, --
decrements it, pointing to the previous character. In this case, it puts it back to the last real character from the terminating null.
Upvotes: 1