reverse a word

This is a discussion on reverse a word within the C Programming forums, part of the General Programming Boards category; hello all, please help me to understand the following code; it compile fine but the it gives the correct result ...

  1. #1
    Registered User
    Join Date
    Sep 2008
    Location
    Manchester, UK
    Posts
    1

    reverse a word

    hello all,

    please help me to understand the following code; it compile fine but the it gives the correct result only for a word of length =< 3. However if I comment out the statement printf("len = %d\n",len) it works fine for all inputs.

    Code:
    # include <stdio.h>
    # include <string.h>
    
    char *ptr;
    
    
      
    int main(int args, char *argv[]){
           
     int len = strlen(argv[1]);
     //printf("len = %d\n",len);
     int j = len - 1, i;
     char ch[len];
             for( ptr=argv[1],i=0; i<len; i++,j--){         
                     
                  ch[i]=*(ptr + j); 
                  }
                              
                     printf(ch);
                     printf("\n");
                 
          system("PAUSE"); 
          }

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    You probably want ch[len+1] and and then put ch[i] = '\0' after the reversing loop.

    Of course, ch[len] is non-standard even for C99 compilers, so if you want to follow C standard coding, you'd have to either use a statically sized buffer [remember to check the length before copying], or call malloc to allocate a suitable size string space [don't forget the +1 for the terminating zero].

    And
    Code:
    printf("%s\n", ch);
    is probably a better solution, as you would get "interesting" results if the user inputs "d%" or some such [and the right combination of % in the input may even cause a crash]

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  2. please help with binary tree, urgent.
    By slickestting in forum C Programming
    Replies: 2
    Last Post: 07-22-2007, 07:55 PM
  3. brace-enclosed error
    By jdc18 in forum C++ Programming
    Replies: 53
    Last Post: 05-03-2007, 05:49 PM
  4. gethostbyaddr() reverse lookups failing (???)
    By Uncle Rico in forum C Programming
    Replies: 9
    Last Post: 08-19-2005, 09:22 AM
  5. Wrong Output
    By egomaster69 in forum C Programming
    Replies: 7
    Last Post: 01-28-2005, 05:44 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21