Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 136,150 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,106 people online right now. Registration is fast and FREE... Join Now!




C: Reversing order of array elements using pointer syntax

 
Reply to this topicStart new topic

C: Reversing order of array elements using pointer syntax

Emper0r
6 Jun, 2007 - 11:35 AM
Post #1

D.I.C Head
**

Joined: 7 Dec, 2006
Posts: 59


My Contributions
Hey guys, basically what I'm trying to do is make a function that takes two arguments, an array of int’s and the number of elements in the array. Then the function is supposed reverse the order of the array elements. However, I'm needing to use only pointer syntax, this means no []'s. Here's what I have so far, if anyone can tell me how exactly I would reverse the order I would greatly appreciate it.

CODE

void reverseArray (int *arr, int nElts)
{
    int i;
    arr=(int*)malloc(nElts*sizeof(int));
    for (i = nElts - 1; i > 0; i--)
      
}

User is offlineProfile CardPM
+Quote Post

Algorythm
RE: C: Reversing Order Of Array Elements Using Pointer Syntax
6 Jun, 2007 - 12:38 PM
Post #2

New D.I.C Head
*

Joined: 17 May, 2007
Posts: 10


My Contributions
Set two pointers: one to the end and one to the beginning. Then move them toward each other, swapping the contents as you go. When the two pointers point to the same place, you're done.
User is offlineProfile CardPM
+Quote Post

rameshg87
RE: C: Reversing Order Of Array Elements Using Pointer Syntax
7 Jun, 2007 - 03:14 AM
Post #3

New D.I.C Head
Group Icon

Joined: 6 Jun, 2007
Posts: 34


Dream Kudos: 50
My Contributions
Well the code that Algorythm said, that should be just like this. i and j are scan throught the array, end is the end address of the array. In pointer arithmetic, for an integer pointer i in C, i++ means to increment the content inside the pointer i be sizeof(int).

CODE

void reverseArray (int *arr, int nElts)
{
    int *i,*j,temp,*end;
    if(nElts>0)
        end=arr+(nElts-1);
    for (i=arr,j=end;j>i;j--,i++)
        {
            temp=*i;
            *i=*j;
            *j=temp;
        }
}


This post has been edited by rameshg87: 7 Jun, 2007 - 07:47 AM
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/1/08 11:05PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month