#include <stdio.h>
int main()
{
char *arr = "This is to test";
printf("\n%c %c ",*(arr++), *开发者_如何转开发(arr++));
return 0;
}
This program outputs h T
rather than outputting h h
. Why is it so?
Using two increment operators in one statement that are independent from each other leads to undefined behaviour because the compiler is free to choose which increment to do first (or rather you didn't give the compiler any hint which one to do first).
Anyway, if you're expecting h h
, it's also wrong to write *(arr++)
twice, because they will be executed both, incrementing arr
twice - and so there will be two different characters printed (arr[0]
and arr[1]
).
Another error is using post-increment which will lead to arr
being incremented after the character was fetched, so it will output T
, not h
.
So a possible solution is this code, using an additional variable:
#include <stdio.h>
int main()
{
char *arr = "This is to test";
char c = *(++arr);
printf("\n%c %c ", c, c);
return 0;
}
In this code, arr
will only be incremented once and the character fetched at this position can be used later.
arr++ is equivalent to arr += 1. You are actually incrementing arr. This is what is happening in your situation.
printf("\n%c %c ",*(arr++), *(arr++));
// ^ ^Evaluates to 0 therefore prints T then increments by 1
// ^Evaluates to 1 therefore prints h and then increments by 1
//Now if where to prinf %s arr it should print "is is to test"
What you want to do is
printf("\n%c %c ",*(arr+1), *(arr+1));
Note: As others have pointed out multiple pre/postfix ++/-- produce undefined behavior (order of evaluation) and should be avoided, although I understand in your situation you were not trying to modify the original array.
Basically because both ++'es move the pointer forward one step after printing, and with the code generated by most compilers today the rightmost one will be done first. and then it will move left.
This is because the unary operator arr++ will cause arr = arr + 1;
and since it is using a postfix operator it will print before assigning the result to arr.
So the steps that are executed are:
- Print T
- move pointer to h
- Print h
- move pointer to i
If you had three in the same line you would get i h T as that would cause it to move a third time.
What I believe you are trying to do is something to the effect of:
printf("\n%c %c ",*(arr+1), *(arr+1));
if u r supposed to get output h h. then u have to write
printf("\n%c %c",*(arr+1),*(arr+1));
but here in your code you updated arr and this increment is post increment so first it assign the value to the function argument then variable will increment. in function
printf("\n%c %c ",*(arr++), *(arr++));
values assigned from left to right on stack so u can imagine like following statement:
printf("\n%c %c ",'h', 'T');
and argument "\n%c %c " will print the output from left to right and u got the output h T.
精彩评论