main()
{
char s[] = "abcdef", *p;
for (p = &s[5]; p >= s; p--) --p*;
puts(s)开发者_开发知识库;
return 0;
}
The compiler says there is a problem with --p* (expected an expression)?????
--p*
doesn't make any sense .
Probably you meant --*p
or --p
?
Your code prints `abcde
when the underlying representation is ASCII. BTW C99 mandates the return type of main()
to be int
in a hosted environment.
Yes, there is a problem with --p*
, it's not valid C, hence the program prints nothing. You're also missing a semi-colon from the end of your char s[] ...
line.
Perhaps you meant something like this:
#include <stdio.h>
int main (void) {
char s[] = "abcdef", *p;
for (p = &s[5]; p >= s; p--) --*p;
puts(s);
return 0;
}
which prints:
`abcde
(assuming you're running in an ASCII environment of course).
And, any book that declares main
as:
main()
instead of one of the two canonical forms, should be tossed out.
One other thing to watch out for, the standard doesn't mandate that pointer aritmetic will work unless both pointers point within the object or one beyond the end. So comparing the final value of p
(which is &(s[-1])
) against s
is not guaranteed to work. A better solution is:
#include <stdio.h>
int main (void) {
char s[] = "abcdef", *p;
for (p = s; *p != 0; p++) --*p;
puts(s);
return 0;
}
The relevant section of C99 is 6.5.6/8
:
When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand.
...
If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.
You're missing a
;
at line 3, and,You probably want
--p
instead of
--p*
The program then prints abcdef
.
Here is an ideone demo.
there's a missing semicolon... i can see it clearly!
精彩评论