Thread: Reversing an array via poiinters in a function

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    28

    Reversing an array via poiinters in a function

    I am currently taking a c programming class, and have just had the worst time trying to figure out how to properly use pointers and functions. I understand how they work in theory, but I just can't seem to get the syntax down right, which has caused no end to my stress. Please, I need some serious help here.

    My teacher has given me a fully written code, and asked me to build three functions to accommodate it. It seems simple in theory, but I can't figure out how to do it. First, I'm passed a 9 length array that I need to reverse (revArray(a)), then I need to return it to its original state (*revElement(a)), and then I need to sort the evens and the odds (evenOdd(a)).

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #define N 9
    
    /* MAIN */
    int main()
    {
    /* Load the array with numbers */
        int a[N];
        int idx;
        int *p = a;
    
        while(p < a + N)
            *p++ = a + N - p;
        printf("Original: ");
        p = a;
        while(p < a + N)
            printf("%2d ",*p++);
    
    /* Part A: Reverse the array */
        revArray(a);
        printf("\nReversed: ");
        p = a;
        while(p < a + N)
            printf("%2d ",*p++);
        printf("\n");
    
    /* Part B: Return elements in reverse order */
    /*    printf("Original: ");*/
        for (idx = 0; idx < N; idx++)
        {
            printf("%2d ",*revElement(a));
        }
        printf("\n");
    
    /*  Part C: Put even numbers first, odd numbers last in the array.  Order of
        the elements is not important as long as all evens are before first odd*/
        printf("Even:     ");
        evenOdd(a);
        p = a;
        while(p < a + N)
            printf("%2d ",*p++);
        printf("\n");
    
    
        return 0;
    }
    Every time I write a function, it doesn't work at all, so can I tell you what I think I should build as a function, and then you could tell me where I'm mistaken?

    For (revArray(a)), I need to make a pointer equal to (a), and then rewrite (a), assigning a [0] = p [N - 1], a [1] = p [N - 2]...a [N] = p [0].

    This is what I wrote

    Code:
    int revArray(int arr)
    {
        int *p = arr;
    
        for (;p < N; p++)
        {
            p = arr + N - arr;
        }
    
        for (arr = p; arr <N; arr++)
        {
            arr = p + N - arr;
        }
    
        return (arr);
    
    }

    I've tried all kinds of different variations, but none work. What am I missing here??

    As for (*revElement(a)), I assume I just have to build the same loop as in (revarray), as a[0] will be put back into a[N]. However, as it's a pointer, I'll need to return (&a), not just (a). Is this correct, or am I wrong on that as well?

    Finally, for (evenOdd(a)), I assume I can just build an array of N+1, and then use %2, and assign all with an output zero to a++, while those with any other output to a-- + N. I've been so stuck on (revarray) that I haven't even had a chance to write that yet, but does it sound like I'm on the right track?

    Again, any help would be massively appreciated.

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    First things first: when you pass an int array to a function, don't say "int arr". That's a single integer. Since you know the size N of the array you could say
    Code:
    void revArray(int arr[N])
    or use a pointer instead, which is not limited to being passed arrays of size N (any size will do).
    Code:
    void revArray(int *arr)
    (In the second case it may make sense to pass in N as well, the size of the array.)

    Now, returning arrays is difficult. However, it sounds like revArray is supposed to reverse the array in-place; in other words, it takes int arr[] and reverses the elements within arr[] and then doesn't have to return anything. Like
    Code:
    void revArray(int arr[N]) {
        // swap arr[0] and arr[N-1]
        // swap arr[1] and arr[N-2]
        // ...
    }
    except in a loop, of course. As an example.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    505
    Your tutor has nodded

    the fucntion needs to be written like this

    Code:
    void revarr(int *arr, int N)
    otherwise it can't know the length of the array.

    You need to think through the logic of how you would do it. Think of an array of one object then an array of two object, three object, and so on.#
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


  4. #4
    Registered User
    Join Date
    Oct 2012
    Posts
    28
    Quote Originally Posted by Malcolm McLean View Post
    Your tutor has nodded

    the fucntion needs to be written like this

    Code:
    void revarr(int *arr, int N)
    otherwise it can't know the length of the array.
    I thought that because it was a pointer, I didn't need to declare the size in there (again, I'm still learning, and this can be a bit overwhelming). I have to do this without modifying the main code, meaning I need it to work with revarray(a), so I guess I'll just use
    Code:
    void revArray(int arr[N])
    You need to think through the logic of how you would do it. Think of an array of one object then an array of two object, three object, and so on.#
    I explained my logic in my first post. Is that wrong? If so, how is it wrong? Keep in mind that I'm supposed to be doing pointer arithmetic, not just writing a standard loop.

  5. #5
    Registered User
    Join Date
    Oct 2012
    Posts
    28
    Quote Originally Posted by dwks View Post
    Now, returning arrays is difficult. However, it sounds like revArray is supposed to reverse the array in-place; in other words, it takes int arr[] and reverses the elements within arr[] and then doesn't have to return anything. Like
    Code:
    void revArray(int arr[N]) {
        // swap arr[0] and arr[N-1]
        // swap arr[1] and arr[N-2]
        // ...
    }
    except in a loop, of course. As an example.
    So how do I do that with pointer arithmetic. I keep trying and nothing works.

    Here's my latest code. Can you please tel,l me what I'm getting wrong?

    Code:
    void revArray(int arr[N])
    {
        int *p = arr;
        int i = 1;
    
        while (p < N)
            *p++ = arr + N - i;
            --i;
    
    
    }
    I've tried both while and for, and I can't make this work at all. The only thing I've gotten to work was this

    Code:
    void revArray(int arr[N])
    {
        int *p = arr;
        int i = 1;
    
        //while (p < N)
        *p++ = arr [N - 1];
    
    
    
    }
    And it replaces arr [0] with the element in arr [N-1]. However, I stick it in a loop, and nothing happens. What am I missing?

  6. #6
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    1)You have to compare p to "arr + N" not N.

    2) use braces more freely. You're missing a set.

    3) You only need to swap up to the middle of the array.

    4) in your code, i is an index, so it needs to use arr with a subscript. Though *(arr + N - i) will also work.
    Last edited by King Mir; 12-05-2012 at 08:18 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  7. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    This code
    Code:
    *p++ = arr [N - 1];
    isn't going to work if you put it in a loop since it always uses arr[N-1]. As King Mir suggested, use arr[N-i] in your loop (or perhaps arr[i] if i counts downwards). However, there are easier ways of doing this. First of all, you may have noticed that arrays and pointers are pretty much the same thing, with interchangeable syntax as far as *(p+i) or p[i] goes. I'd either go with an all-out pointers version that looks something like
    Code:
    int *p = arr;
    int *q = arr + N-1;
    
    // in a loop, swap p and q
    int temp = *p;
    *p = *q;
    *q = temp;
    p++; q --;
    or an all-out array version, something like
    Code:
    for(i = 0; ...) {
        // swap arr[i] and arr[N-1-i]
        int temp = arr[i];
        arr[i] = arr[N-1-i];
        arr[N-1-i] = temp;
    }
    I think the swapping is necessary if you're reversing into the same array. Otherwise with just "*p = arr[i]" you are losing the data that was at *p.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reversing output in this function
    By rogster001 in forum C Programming
    Replies: 8
    Last Post: 02-07-2008, 06:36 AM
  2. Reversing a c-string with a function
    By patricio2626 in forum C++ Programming
    Replies: 3
    Last Post: 04-01-2007, 11:00 PM
  3. string array reversing...
    By cit in forum C Programming
    Replies: 4
    Last Post: 03-28-2002, 03:09 AM
  4. reversing elements of an array
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 02-18-2002, 09:04 PM
  5. Reversing a Multi-D Array
    By Bradley33 in forum C++ Programming
    Replies: 1
    Last Post: 11-19-2001, 11:37 AM