![]() |
|
|
|
|
|
|
3
26th October 15:38
External User
Posts: 1
|
thats enourmous complicated. fgets() nearly
does the same thing. That piece of code is, ugly and misleading. It does what it should do, but every programmer has to look very carefully to convice itself that it is indeed correct. while( ch ... { .... } a[i] = '\0'; /* terminate the character string */ i--; for( ; i >= 0; --i ) printf( "%c", a[i] ); Now it's clearer, what's going on. Note that the variable 'len' isn't used anymore. This is especially good, because len doesn't hold what it's name implies: the length of the string. In what you have written, len is simply a (misleading) way to write 0 or '\0'; If you have to do the same with pointers, then you first need a pointer to the last character in the string. Since you know that there are i charcaters in the string, you get that pointer with: char* pTmp = &a[i]; Now that you have that pointer, dereferencing it will yield the character: printf( "%c", *pTmp ); All that is left, is to envelope the pirintf in a loop and decrement the pointer until, you are at the very beginning of the string. How do you know that you are at the beginning? Simple: When the pointer equals &a[0], or simpler written a. char* pTmp = &a[i+1]; do { --pTmp; printf( "%c", *pTmp ); } while( pTmp != a ); I changed the start condition to start one behind the last character (where the '\0' is located), in order to decrement the pointer as the first action in the loop. This is important because for the first character in the array, we first have to print the character, before the test in the while condition terminates the loop. -- Karl Heinz Buchegger kbuchegg@gascad.at |
|