Thread: a function which takes a character array and reverses it

  1. #1
    Registered User
    Join Date
    Sep 2013
    Posts
    15

    a function which takes a character array and reverses it

    this was a question from my first exam and it says

    write a c function which takes a string(as a character array, null terminated) and reverses it. it doesn't print the reversed string -- it modifies the given string so that it is reversed.

    Code:
    void reverse(char array[])
    {
            char tmp;
            int i, j;
            for(i=0;i<strlen(array); i++)
            {
                    for(j=strlen(array)-1;j>=0;j--)
                    {
                            tmp = array[i];
                            array[i] = array[j];
                            array[j] = tmp;
                    }
            }
    }
    how come this doesn't work?

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    How about you explain why you think it SHOULD work?

    That's not an idle question. In trying to answer that - properly - you will almost certainly uncover the reason that it does not work.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    You can also use a debugger or use a debugging print statement to see what is happening at each step. Then it should be easier to see what is happening:

    Code:
    printf("i=%d, j=%d, array: %s\n", i, j, array);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 11-28-2011, 03:39 PM
  2. Passing character array into function
    By cactuar in forum C++ Programming
    Replies: 9
    Last Post: 10-23-2009, 02:10 PM
  3. Replies: 1
    Last Post: 10-21-2007, 07:44 AM
  4. Replies: 9
    Last Post: 01-02-2007, 04:22 PM
  5. passing a character array through a function
    By volk in forum C++ Programming
    Replies: 4
    Last Post: 04-06-2003, 05:47 PM