This is so horrible and faulty that I have to attach the
following. Don't forget to #include <strings.h>. Note that it
returns strlen.
/* ======================= */
/* reverse string in place */
size_t revstring(char *stg)
{
char *last, temp;
size_t lgh;
lgh = strlen(stg);
if (lgh > 1) {
last = stg + lgh; /* points to '\0' */
while (last-- > stg) {
temp = *stg; *stg++ = *last; *last = temp;
}
}
return lgh;
} /* revstring */
I have edited it a little bit to get pointer to pointer as function
argument and combined it with my get_single_word program and it works
little strange though. Also, your function is much easier to read IMHO:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
enum { WORD_SIZE = 28 };
enum { GSW_OK, GSW_ENOMEM, GSW_ENORESIZE } ;
int get_single_word( char** );
size_t revstring( char** );
int main(void)
{
char *word;
while( (GSW_OK == get_single_word(&word)) && (*word) )
{
revstring( &word );
printf("Reversed: [ %s ]\n", word);
}
return 0;
}
/* reverse string in place */
size_t revstring(char **stg)
{
char *last, temp;
size_t lgh;
lgh = strlen(*stg);
if (lgh > 1) {
last = *stg + lgh; /* points to '\0' */
while (last-- > *stg)
{
temp = **stg;
**stg++ = *last;
*last = temp;
}
}
return lgh;
}
int get_single_word( char** ppc )
{
unsigned ele_num;
int ch;
size_t word_length, word_length_interval;
char* word_begin;
char* new_mem;
ele_num = 0;
word_length = WORD_SIZE;
word_length_interval = 2;
*ppc = malloc(word_length * sizeof(**ppc));
word_begin = *ppc;
if( NULL == ppc )
{
return GSW_ENOMEM;
}
while( (EOF != (ch = getchar())) && isspace(ch) )
{
continue; /* trailing whitespace */
}
if( EOF != ch )
{
*word_begin++ = ch;
ele_num = 1;
}
while( (EOF != (ch = getchar())) && (! isspace(ch)) )
{
if( (word_length - 1) == ele_num++ )
{
new_mem = realloc( *ppc, (word_length_interval * word_length * sizeof **ppc) );
*ppc = new_mem;
if( new_mem )
{
word_begin = new_mem + (word_begin - *ppc);
word_length *= word_length_interval;
*ppc = new_mem;
}
else
{
*word_begin = '\0';
return GSW_ENORESIZE;
}
}
*word_begin++ = ch;
}
*word_begin = '\0';
return GSW_OK;
}
=================== OUTPUT =====================
[arnuld@dune ztest]$ gcc -ansi -pedantic -Wall -Wextra reverse-string.c
[arnuld@dune ztest]$ ./a.out
Ben
Reversed: [ neB ]
CBFalconer
Reversed: [ rBFalconeC ]
comp.kang.c++
Reversed: [ +omp.kang.c+c ]
[arnuld@dune ztest]$