Loops in C challenge: can it be done another way?
Hi all C experts (please don't shoot, I'm no C programmer anymore but from time to time I have a question that pops in my mi开发者_如何学Pythonnd)
I was reading another question (How to print an entered string backwards in C using only a for loop).
The "simplest" and most logical answer is
for (x = end; x >= 0; --x) {
printf("%c", word[x]);
}
But I was wondering if there wasn't a way to achieve the same goal but staying closer to the original loop poseted:
for (x = word[end]; x >= word[0]; x--) {
printf("%c", x);
}
I don't know enough C to work it out, but couldn't we play with the arrays pointers to loop through
char * wordp;
for(wordp = &word[end]; /*something*/; wordp--){\
printf("%c", &wordp);
}
P.S.: I don't really care if it is a forwards or backwards loop.
P.P.S.: Sorry if I made obvious C mistakes in the pointers; point them out in the comment and I'll edit them. ;)
Jason
Absolutely.
char *wordp;
for(wordp = word + end; wordp >= word; wordp--){
printf("%c", *wordp);
}
for (x = word[end]; x >= word[0]; x--) {
printf("%c", x);
}
will not work, as word[end] is equivalent to *(word + end). It's already being dereferenced, so x will be set to the value of the last char, and will loop until it equals the char value of the first char. In short, it makes no sense.
Try:
char * wordp;
for(wordp = (word + end); wordp >= word; wordp--){\
printf("%c", *wordp);
}
Remember that an array is simply a pointer to its first item.
You can do:
char * wordp;
for(wordp = &word[end]; wordp >= word ; wordp--){\
printf("%c", *wordp);
}
Real programmers use recursion:
void revputs(char *s) {
if (*s) { revputs(s + 1); putchar(*s); }
}
精彩评论