Thread: Could someone explain this code, string

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    27

    Could someone explain this code, string

    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define MAX_LEN 80
    
    void reverse_string(char str[])
    {
    	int i, len = strlen(str);
    	for(i = 0; i < (len / 2); i++)
    	{
    		char ch = str[i];
    		str[i] = str[(len - 1) - i];
    		str[(len - 1) - i] = ch;
    	}
    }
    
    int main()
    {
    	char str[MAX_LEN+1];
    
    	printf("Enter string:\n");
    	scanf("%s", str);
    
    	reverse_string(str);
    
    	printf("%s\n", str);
    
    	return 0;
    }
    This is how you can reverse a string using a For loop. However, I don't understand this part:

    Code:
    for(i = 0; i < (len / 2); i++)
    	{
    		char ch = str[i];
    		str[i] = str[(len - 1) - i];
    		str[(len - 1) - i] = ch;
    	}
    Could someone please explain it to me so I can understand it? Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Start with a string of some short length (say 2 and 3), then
    - run the code by hand and observe what happens
    - run the code you have in a debugger and observe
    - put some extra printf statements in to print the values being moved.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2003
    Posts
    27
    Originally posted by Salem

    - run the code you have in a debugger and observe
    How do I do that?

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by sjalesho
    How do I do that?
    Read your compiler's documents and see if it came with a debugger. Then read how to use it. Otherwise, take one of the other two steps mentioned.

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Oct 2003
    Posts
    27
    I'm using Cygwin on Windows. I just compile using gcc <program.c> and I create the files in Windows notebook and save them as program.c

    I don't have these advanced options to let the compiler show me it step by step. Nobody willing to explain that little piece of code line by line? Because I don't understand it.

  6. #6
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Originally posted by sjalesho
    I don't understand this part:
    Code:
    for(i = 0; i < (len / 2); i++)
        {
            char ch = str[i];
            str[i] = str[(len - 1) - i];
            str[(len - 1) - i] = ch;
        }
    Could someone please explain it to me so I can understand it?
    The three lines in the loop body swap characters. For example:
    Code:
    str[] = "world"
    len = 5
    len / 2 = 2
    
    str[0]  str[1]  str[2]  str[3]  str[4]  str[5]
     'w'     'o'     'r'     'l'     'd'     '\0'
      ^       ^               ^       ^
      |       |               |       |
      |       +----- i=1 -----+       |  (len - 1) - i = (5 - 1) - 1 = 4 - 1 = 3
      |                               |
      +------------- i=0 -------------+  (len - 1) - i = (5 - 1) - 0 = 4 - 0 = 4
    Using a temporary variable to help simplify the end character index, and adding printfs, as previously suggested, you might have something like this.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    void reverse_string(char str[])
    {
       int i, len = strlen(str);
       printf("str = \"%s\", len = %d\n", str, len);
       for ( i = 0; i < (len / 2); i++ )
       {
          char ch;
          int x = (len - 1) - i;
          printf("i = %d, x = %d: str[i] = '%c' <-> str[x] = '%c' -> ",
                 i, x, str[i], str[x]);
          ch = str[i];
          str[i] = str[x];
          str[x] = ch;
          printf("str = \"%s\"\n", str);
       }
    }
    
    int main()
    {
       char str[] = "programmer";
       reverse_string(str);
       printf("%s\n", str);
       return 0;
    }
    
    /* my output
    str = "programmer", len = 10
    i = 0, x = 9: str[i] = 'p' <-> str[x] = 'r' -> str = "rrogrammep"
    i = 1, x = 8: str[i] = 'r' <-> str[x] = 'e' -> str = "reogrammrp"
    i = 2, x = 7: str[i] = 'o' <-> str[x] = 'm' -> str = "remgramorp"
    i = 3, x = 6: str[i] = 'g' <-> str[x] = 'm' -> str = "remmragorp"
    i = 4, x = 5: str[i] = 'r' <-> str[x] = 'a' -> str = "remmargorp"
    remmargorp
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  7. #7
    Registered User
    Join Date
    May 2002
    Posts
    132
    change the program to do this:

    Code:
    for(i = 0; i < (len / 2); i++)
    	{
    		char ch = str[i];
                                    printf("ch: %c\n", ch);
    		str[i] = str[(len - 1) - i];
                                    printf("%d of str is being changed to %c which came from position %d in str\n", i, str[(len - 1) - i], (len - 1) - i);
    		str[(len - 1) - i] = ch;
                                    printf("ch is being placed in position %d\n", (len - 1) - i);
                                    _getch();
    	}
    Each change will force you to hit any key, thus allowing you to watch each and every step (with output) so then you know whats happening. This is what Salem was suggesting you do.

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > I'm using Cygwin on Windows
    Well I suggest you run the 'install' application and select from the development tools the 'gdb' program. This is the debugger.

    Example session
    Code:
    $ gcc -ggdb prog.c
    $ gdb a.exe
    GNU gdb 2003-09-20-cvs (cygwin-special)
    Copyright 2003 Free Software Foundation, Inc.
    GDB is free software, covered by the GNU General Public License, and you are
    welcome to change it and/or distribute copies of it under certain conditions.
    Type "show copying" to see the conditions.
    There is absolutely no warranty for GDB.  Type "show warranty" for details.
    This GDB was configured as "i686-pc-cygwin"...
    (gdb) break main
    Breakpoint 1 at 0x401112: file munch.c, line 24.
    (gdb) run tmp
    Starting program: /home/Administrator/test/users/a.exe tmp
    
    Breakpoint 1, main (argc=2, argv=0xa041df0) at munch.c:24
    24          FILE *fp = fopen( argv[1], "rb" );
    (gdb) next
    26          while ( (ch=fgetc(fp)) != EOF ) {
    (gdb)
    27              if ( ch != 0x0D ) fputc( ch, stdout );
    $ gdb a.exe
    GNU gdb 2003-09-20-cvs (cygwin-special)
    Copyright 2003 Free Software Foundation, Inc.
    GDB is free software, covered by the GNU General Public License, and you are
    welcome to change it and/or distribute copies of it under certain conditions.
    Type "show copying" to see the conditions.
    There is absolutely no warranty for GDB.  Type "show warranty" for details.
    This GDB was configured as "i686-pc-cygwin"...
    (gdb) break main
    Breakpoint 1 at 0x401112: file munch.c, line 24.
    (gdb) run tmp
    Starting program: /home/xxx/test/users/a.exe tmp
    
    Breakpoint 1, main (argc=2, argv=0xa041df0) at munch.c:24
    24          FILE *fp = fopen( argv[1], "rb" );
    (gdb) next
    26          while ( (ch=fgetc(fp)) != EOF ) {
    (gdb)
    27              if ( ch != 0x0D ) fputc( ch, stdout );
    (gdb) print argv[1]
    $1 = 0x22ff02 "tmp"
    (gdb) print ch
    $2 = 32
    (gdb) bt
    #0  main (argc=2, argv=0xa041df0) at munch.c:27
    > Nobody willing to explain that little piece of code line by line?
    Well we could, but at some point, you've got to figure this stuff out for yourself, otherwise you'll never be able to write a meaningful program.

    It's a "give a man a fish" vs. "teach a man to fish" deal.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you check what is wrong with this code
    By Ron in forum C++ Programming
    Replies: 4
    Last Post: 08-01-2008, 10:59 PM
  2. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 03:40 AM
  3. RicBot
    By John_ in forum C++ Programming
    Replies: 8
    Last Post: 06-13-2006, 06:52 PM
  4. Replies: 3
    Last Post: 03-27-2004, 12:15 PM
  5. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM