Thread: Sending array's to functions by reference or pointers

  1. #16
    C/C++ homeyg's Avatar
    Join Date
    Nov 2004
    Location
    Louisiana, USA
    Posts
    209
    Hmmm, I was trying to use the i's to try and fix the copying over problem and I guess I never got a chance to clean up the code a little. Here, how's this:

    Code:
    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    void stringReverser(char* array, int len);
    
    int main()
    {
        char array[50];
        
        cout<<"Please enter a string to have it reversed: ";
        cin.get(array,49);
        int length = strlen(array);
        stringReverser(array,length);
        cout<<"Your string reversed is: "<<array<<endl;
        
        system("PAUSE");
        return 0;
    }
    
    void stringReverser(char* array, int len)
    {
        char newArray[50];
        
        int j = len-1;
        for(int i = 0;i<len;i++,j--)
        {
            newArray[i]=array[j];
        }
        for(int i = 0;i<len;i++)
        {
            array[i]=newArray[i];
        }            
    }
    Last edited by homeyg; 12-27-2004 at 02:28 PM.

  2. #17
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    here's an alternate version based on Salems suggestion:
    Code:
    void stringReverser(char* array, int len)
    {
       char ch;
       for(int i = 0; i < len/2; ++i)
       {
    	  //swap chars in same space without temporary holding array.
    	  ch = array[x];
    	  array[x] = array[len - 1 - x];
    	  array[len - 1 - x] = ch;
       }
    };
    If you are allowed to use standard functions, you could consider using std::swap() from the std::algorithm header instead of the three line swap code in the for loop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. functions using arrays
    By trprince in forum C Programming
    Replies: 30
    Last Post: 11-17-2007, 06:10 PM
  2. Pointers and reference passing
    By Denis Itchy in forum C++ Programming
    Replies: 4
    Last Post: 12-13-2002, 01:36 AM
  3. passing arrays into functions by reference
    By Aran in forum C++ Programming
    Replies: 7
    Last Post: 05-25-2002, 09:55 PM
  4. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM
  5. pointers, functions, parameters
    By sballew in forum C Programming
    Replies: 3
    Last Post: 11-11-2001, 10:33 PM