newbie: help with string reversal 
Author Message
 newbie: help with string reversal

Hello. After a considerable hiatus, I am trying to relearn C. I
have a small program whose purpose is to reverse a string. It compiles
fine but fails to reverse the string. I know that there are better
ways to do this, but I am curious as to why the nested for loops fail.
Any clues are appreciated. Thanks.

John.  

#include <stdio.h>

char name[]="This is a string reversal program.";

main ()
{
 register int i, j;
 int max = sizeof(name);
 char copy[max];

  printf("%s\n", name);
  printf("This is the current size of the string, in bytes: %d\n", max);

        for (i=0; i < max ; ++i)
                for (j=max ; j > 0 ; --j)
                 copy[j] = name[i];

  printf("This is the reversed string: %s\n", copy);
  printf("This is the original: %s\n", name);

Quote:
}



Sat, 12 Jan 2002 03:00:00 GMT  
 newbie: help with string reversal

The NNTP protocol allows a message to have a body, too. You should take
advantage of this feature even if your Subject header hints at the
issue at hand.
To answer the question I think you wanted to ask, have you tried a loop?

Gergo

--

Quote:
> No manual is ever necessary.

May I politely interject here: BULLSHIT.  That's the biggest Apple lie of all!
(Discussion in comp.os.linux.misc on the intuitiveness of interfaces.)

GU d- s:+ a--- C++>$ UL+++ P>++ L+++ E>++ W+ N++ o? K- w--- !O !M !V
PS+ PE+ Y+ PGP+ t* 5+ X- R>+ tv++ b+>+++ DI+ D+ G>++ e* h! !r !y+



Sat, 12 Jan 2002 03:00:00 GMT  
 newbie: help with string reversal
Well, you may want to try something easier:

#include <stdio.h>

void print_backwards(char *str)
{
 if(*str) {
  print_backwards(str+1);
  putchar(*str);
 }

Quote:
}

int main()
{
 print_backwards("This is a forward string.");
 printf("\n");
 return 0;

Quote:
}

--

Paul Lutus
www.arachnoid.com


Quote:
> Hello. After a considerable hiatus, I am trying to relearn C. I
> have a small program whose purpose is to reverse a string. It compiles
> fine but fails to reverse the string. I know that there are better
> ways to do this, but I am curious as to why the nested for loops fail.
> Any clues are appreciated. Thanks.

> John.

> #include <stdio.h>

> char name[]="This is a string reversal program.";

> main ()
> {
>  register int i, j;
>  int max = sizeof(name);
>  char copy[max];

>   printf("%s\n", name);
>   printf("This is the current size of the string, in bytes: %d\n", max);

> for (i=0; i < max ; ++i)
>        for (j=max ; j > 0 ; --j)
> copy[j] = name[i];

>   printf("This is the reversed string: %s\n", copy);
>   printf("This is the original: %s\n", name);
> }



Sat, 12 Jan 2002 03:00:00 GMT  
 newbie: help with string reversal

   Well, you may want to try something easier:

   void print_backwards(char *str)
   {
    if(*str) {
     print_backwards(str+1);
     putchar(*str);
    }
   }



   > Hello. After a considerable hiatus, I am trying to relearn C. I
   > have a small program whose purpose is to reverse a string. It compiles

That doesn't reverse the string, Paul.  Rather, it prints the string
in reverse.  The difference is the difference between printf() and
sprintf().

  [deletia]
--
"You call this a *C* question? What the hell are you smoking?" --Kaz



Sat, 12 Jan 2002 03:00:00 GMT  
 newbie: help with string reversal

Quote:


>   Well, you may want to try something easier:

>   void print_backwards(char *str)
>   {
>    if(*str) {
>     print_backwards(str+1);
>     putchar(*str);
>    }
>   }



>   > Hello. After a considerable hiatus, I am trying to relearn C. I
>   > have a small program whose purpose is to reverse a string. It compiles

>That doesn't reverse the string, Paul.  Rather, it prints the string
>in reverse.  The difference is the difference between printf() and
>sprintf().

Of course you're right Ben but I just want to applaud anyway. For long time
C devotees (if I may presume) this sort of thing may seem to be 'old hat'
but continue to amuse me, so: thanks, Paul.
Regards,
Greg Martin


Sat, 12 Jan 2002 03:00:00 GMT  
 newbie: help with string reversal
Okay, okay. How about this:

#include <stdio.h>

void swapString(char *a, char *b)
{
 char c;
 if(a < b) {
  c = *a;
  *a = *b;
  *b = c;
  swapString(a+1,b-1);
 }

Quote:
}

int main()
{
 char test[64] = "This is a test.";
 swapString(test,test+strlen(test)-1);
 printf("%s\n",test);
 return 0;

Quote:
}

--

Paul Lutus
www.arachnoid.com


Quote:

>    Well, you may want to try something easier:

>    void print_backwards(char *str)
>    {
>     if(*str) {
>      print_backwards(str+1);
>      putchar(*str);
>     }
>    }



>    > Hello. After a considerable hiatus, I am trying to relearn C. I
>    > have a small program whose purpose is to reverse a string. It
compiles

> That doesn't reverse the string, Paul.  Rather, it prints the string
> in reverse.  The difference is the difference between printf() and
> sprintf().

>   [deletia]
> --
> "You call this a *C* question? What the hell are you smoking?" --Kaz



Sat, 12 Jan 2002 03:00:00 GMT  
 newbie: help with string reversal
<< Ooh, I *like* that solution, Paul.  BTW I really wish you'd get an email
address, so that I wouldn't have to post this sort of response. >>

I've been getting an increasing amount of traffic on my message board
vis-a-vis the recent "Paul is the devil" thread (half pro, half con, most
{*filter*}). I am now less likely than ever to provide an e-mail address, sorry
to say.

Were this not true, I would of course have a policy of routing "Rotten code,
Paul" messages to my e-mail, and requiring "Great code, Paul" as a public
post :)

--

Paul Lutus
www.arachnoid.com


Quote:

>    Okay, okay. How about this:

>    #include <stdio.h>

>    void swapString(char *a, char *b)
>    {
>     char c;
>     if(a < b) {
>      c = *a;
>      *a = *b;
>      *b = c;
>      swapString(a+1,b-1);
>     }

>    > That doesn't reverse the string, Paul.  Rather, it prints the string
>    > in reverse.  The difference is the difference between printf() and
>    > sprintf().

>    >   [deletia]

> Ooh, I *like* that solution, Paul.  BTW I really wish you'd get an
> email address, so that I wouldn't have to post this sort of response.
> --
> Dann Corbit on comp.lang.c:
> "Once you have leached enough [from c.l.c], you may find that others are
>  then able to attach their razor-sharp hooks into your meaty extremities
>  and you can provide them with a gruesome meal yourself."



Sat, 12 Jan 2002 03:00:00 GMT  
 newbie: help with string reversal

Quote:

>Hello. After a considerable hiatus, I am trying to relearn C. I
>have a small program whose purpose is to reverse a string. It compiles
>fine but fails to reverse the string. I know that there are better
>ways to do this, but I am curious as to why the nested for loops fail.
>Any clues are appreciated. Thanks.

>John.  

>#include <stdio.h>

>char name[]="This is a string reversal program.";

>main ()

Consider using int main(void), as implicit int will probably be illegal
soon.

Quote:
>{
> register int i, j;
> int max = sizeof(name);
> char copy[max];

gcc warns about this, saying: ANSI C forbids variable-size array `copy'.
I fixed (or just silenced?) this by changing the above to
char copy[sizeof(name)];
This is a declaration of an array of max elements indexed 0 to max-1. If
you really only wanted a clue, stop reading now!

Quote:
>  printf("%s\n", name);
>  printf("This is the current size of the string, in bytes: %d\n", max);

>    for (i=0; i < max ; ++i)
>                    for (j=max ; j > 0 ; --j)
>             copy[j] = name[i];

At the first iteration, you are trying to write to copy[max], which is a
memory area you don't own. If you want to keep the nested loops, change
the second one to for (j=max-2 ; j >= 0 ; --j). Use -2 because
copy[max-1], the last element of the array, needs to hold a terminating
'\0' character, and you don't want to copy name's NUL character. Also
note that at any point in time, j==max-2-i, so you only need one loop.
Since this prose description isn't very clear, I'll illustrate it with
some code:

for(i=0; i<max-1; i++)
    copy[max-i-2]=name[i];
copy[max-1]='\0';

Quote:

>  printf("This is the reversed string: %s\n", copy);
>  printf("This is the original: %s\n", name);

Return a value from main():

return 0;

Quote:
>}

--
[From an announcement of a congress of the International Ontopsychology
Association, in Rome]:

The Ontopsychological school, availing itself of new research criteria and
of a new telematic epistemology, maintains that social modes do not spring
from dialectics of territory or of class, or of consumer goods, or of means
of power, but rather from dynamic latencies capillarized in millions of
individuals in system functions which, once they have reached the event
maturation, burst forth in catastrophic phenomenology engaging a suitable
stereotype protagonist or duty marionette (general, president, political
party, etc.) to consummate the act of social schizophrenia in mass genocide.

GU d- s:+ a--- C++>$ UL+++ P>++ L+++ E>++ W+ N++ o? K- w--- !O !M !V
PS+ PE+ Y+ PGP+ t* 5+ X- R>+ tv++ b+>+++ DI+ D+ G>++ e* h! !r !y+



Sun, 13 Jan 2002 03:00:00 GMT  
 newbie: help with string reversal
: Hint:
: Take the first letter and replace it with the last one, while replacing the
: last one with the first one.  You will need a temporary for this.  Then,
: replace the second letter with the second to last and vice versa.  Continue
: till you hit the middle.  Don't forget even/odd.

I wrote a little routine for my own practice which does this, and in my
construct it makes no difference whether the string is has an odd or
even number of characters.  Am I missing some subtle (or not so subtle)
bug? Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverse_string( char *a, size_t size )
{
    int i, j;
    char tmp;

    j = size - 1;
    for( i = 0, j = size - 2; i < size / 2; i++, j-- ) {
       tmp = a[i];
       a[i] = a[j];
       a[j] = tmp;
   }

   return;

Quote:
}

int main( void )
{
     char data[] = "Reverse this bunch of data!";

     printf( "sizeof data = %d bytes\n", sizeof(data) );
     printf( "Initial string: %s\n", data );

     reverse_string( data, sizeof(data) );
     printf( "Reversed string: %s\n", data );

     reverse_string( data, sizeof(data) );
     printf( "Re-reverse string: %s\n", data );

     exit( EXIT_SUCCESS );

Quote:
}

Constructive comments appreciated.

Paul

--
Pursuant to US Code, Title 47, Chapter 5, Subchapter II, Sec. 227, any
and all nonsolicited commercial E-mail sent to this address is subject to
a download and archival fee in the amount of $500 US.  E-mailing denotes
acceptance of these terms.



Sun, 13 Jan 2002 03:00:00 GMT  
 newbie: help with string reversal

   Okay, okay. How about this:

   #include <stdio.h>

   void swapString(char *a, char *b)
   {
    char c;
    if(a < b) {
     c = *a;
     *a = *b;
     *b = c;
     swapString(a+1,b-1);
    }

   > That doesn't reverse the string, Paul.  Rather, it prints the string
   > in reverse.  The difference is the difference between printf() and
   > sprintf().
   >
   >   [deletia]

Ooh, I *like* that solution, Paul.  BTW I really wish you'd get an
email address, so that I wouldn't have to post this sort of response.
--
Dann Corbit on comp.lang.c:
"Once you have leached enough [from c.l.c], you may find that others are
 then able to attach their razor-sharp hooks into your meaty extremities
 and you can provide them with a gruesome meal yourself."



Sun, 13 Jan 2002 03:00:00 GMT  
 newbie: help with string reversal


Quote:
> Here is something I clipped from some old post by some blithering idiot:

<reluctant snip of neat code>

But I think everyone so far has missed the point. Since the OP asked for
help with string reversal, don't you think the right answer would be

void revstring(char *p)
{
  strcpy(p, "gnirts");

Quote:
}

/me ducks and runs for cover...


Sun, 13 Jan 2002 03:00:00 GMT  
 newbie: help with string reversal


Quote:
> << Ooh, I *like* that solution, Paul.  BTW I really wish you'd get an
email
> address, so that I wouldn't have to post this sort of response. >>

> I've been getting an increasing amount of traffic on my message board
> vis-a-vis the recent "Paul is the devil" thread (half pro, half con, most
> {*filter*}). I am now less likely than ever to provide an e-mail address,

sorry to say.

Paul, this may come as a shock to you, but many of us get increasing
amounts of email that have no relevance or interest for us, but it doesn't
stop us from publishing our email address on principle. I used to slightly
mung my email address in an effort to stop spam, but stopped doing it when
I realised how irritated I got when replying to other people who did this.

A compromise (and thus unsatisfactory to all parties) suggestion: why not
compile a list of those people here from whom you think emails would be
likely to be non-{*filter*} at the very least - people whom you trust, in
other words - and email them your email address?

Or don't you trust /anyone/? That would be rather sad, if true.

Quote:
> Were this not true, I would of course have a policy of routing "Rotten
code,
> Paul" messages to my e-mail, and requiring "Great code, Paul" as a public
> post :)

Hmmm. I'm thinking of having my own policy, of routing all postings from
people who won't supply an email address to /dev/null, in the same way that
I re-route those tricksy emails that seem to be from me to me, but
nevertheless want me to spend dollars I haven't got (I use pounds) on hair
cream or (ironically) anti-spam services.

--
Richard Heathfield

The bug stops here.



Sun, 13 Jan 2002 03:00:00 GMT  
 
 [ 25 post ]  Go to page: [1] [2]

 Relevant Pages 

1. newbie needs help to strings, strings, strings

2. String Reversal

3. Bit order reversal function help

4. newbie needs string help

5. please help newbie string replacement in big file

6. Newbie: Help with Strings

7. newbie help with strings.

8. newbie: help with a string

9. newbie help with strings

10. newbie - help with string

11. pls help a newbie with stupid string

12. eval(string)?, or, 'nother newbie needs help

 

 
Powered by phpBB® Forum Software