Thread: reversing elements of array using a pointer

  1. #1
    Unregistered
    Guest

    reversing elements of array using a pointer

    this is my source code why wont it reverse it??? all it does is print it out the same way as before.....help its due tommorow thanx.....

    #include <stdio.h>

    #define MAX 5

    void exchange(int *pAry,int *first,int size);

    int main (void)
    {
    int ary[MAX]={6,82,7,3,21};
    int *pWalk;
    int *pLast;

    pLast = ary + MAX - 1;

    printf("Your Elements:\n");
    for( pWalk=ary; pWalk<=pLast; pWalk++ )
    printf("%3d",*pWalk);
    printf("\n\n");

    exchange (ary,pWalk,MAX-1);

    printf("Your Elements in Reverse:\n");
    for ( pWalk=ary; pWalk<=pLast; pWalk++ )
    printf("%3d",*pWalk);
    printf("\n\n");

    return 0;
    }

    void exchange (int *pAry,int *first,int size)
    {
    int *temp;
    int *mid;
    int *pLast;

    mid = (pAry+3);
    pLast = pAry + size - 1;

    for ( first=pAry; first<mid; first++, pLast--)
    {
    temp=first;
    first=pLast;
    pLast=first;
    }

    return;
    }

  2. #2
    Unregistered
    Guest
    For one, change declarations like this:

    pLast = ary + MAX - 1;

    To

    pLast = &ary[MAX - 1];

    Try this for similar 'pLast' and 'pWalk' (if needed) declarations.

  3. #3
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    Why? "pLast = ary + MAX - 1; " is very clear, this really shows that you understand calculating with pointers.

    Wrong is the reversing function. This one is better.

    Code:
    void reverse (int *array, int size)
    {
        int temp;
        int index;  
       
        for (index = 0; index < (size / 2); index++)
        {
                temp = array [index];
                array [index] = array [size - index - 1];
                array [size - index - 1] = temp;
        }
    }
    A hint about debugging. Use printf's. Use them to display important data at certain places in the code. You can also use them to debug pointer calculations, if a pointer p is declared as int *p, then printf ("%d\n", p); prints out the address. So in that way you can check if calculations are going right.

  4. #4
    Unregistered
    Guest

    Talking

    thanx shiro i got it to finnaly work.....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. using realloc for a dynamically growing array
    By broli86 in forum C Programming
    Replies: 10
    Last Post: 06-27-2008, 05:37 AM
  3. Quick Pointer Question
    By gwarf420 in forum C Programming
    Replies: 15
    Last Post: 06-01-2008, 03:47 PM
  4. Pointer to array of string and Array of Pointer to String
    By vb.bajpai in forum C Programming
    Replies: 2
    Last Post: 06-15-2007, 06:04 AM
  5. Pros pls help, Pointer to array
    By kokopo2 in forum C Programming
    Replies: 7
    Last Post: 08-17-2005, 11:07 AM