Quote:
Originally Posted by rtmistler
Write a C program, using no library calls, allocating no memory, using no temporary holding variables, to reverse a string in place.
|
That had never crossed my mind! As the OP has not returned but the thread remains of interest, my feeble attempt...
Code:
/* Reverse string argv[1] in place with no lib call, no allocation, no temp vars */
int main(int argc, char **argv)
{
if(argc<2)
return 0;
for(argc=0; *(argv[1]+argc); argc++)
;
*(argv[0])=0;
while(*(argv[0])<--argc)
{
*(argv[1]+*(argv[0]))^=*(argv[1]+argc);
*(argv[1]+argc)^=*(argv[1]+*(argv[0]));
*(argv[1]+*(argv[0]))^=*(argv[1]+argc);
++*(argv[0]);
}
return 0;
}
Use a debugger to show the result as suggested by rtmistler (or add the stdio lib for printf()).
Should check if the string is longer than can be indexed by char, but...
UPDATE: Following is same but more readable, includes overflow guard, useful exit values...
Code:
/* Reverse string in place, no lib calls, allocs or tmp vars */
#include <limits.h>
#define HEAD *argv[0]
#define TAIL argc
#define SPTR argv[1]
#define NO_STRING_ERR 1
#define TOO_LONG_ERR 2
int main(int argc, char **argv)
{
if(argc<2)
return NO_STRING_ERR;
for(TAIL=0; *(SPTR+TAIL); ++TAIL)
;
if(TAIL/2 > CHAR_MAX)
return TOO_LONG_ERR;
HEAD=0;
while(HEAD<--TAIL)
{
*(SPTR+HEAD) ^= *(SPTR+TAIL);
*(SPTR+TAIL) ^= *(SPTR+HEAD);
*(SPTR+HEAD) ^= *(SPTR+TAIL);
++HEAD;
}
return 0;
}