[gameprogrammer] Re: passing pointer to array

Or you could use C++ references, and C++ container classes. A
references is similar to a pointer, but can never be NULL, and one
cannot use pointer arithmetic on them. In addition, a C++ reference
cannot be made reference another variable after definition.

First, your code with references.

struct Array
{
    int length;
    int *data;
};

// prefer to pass complex types by const reference
int fileToArray(const std::string &filename, Array &array)
{
    std::ifstream file(filename.c_str());
    file >> array.length;
    array.data = new int[array.length];
    for( int i = 0 ; i < array.length ; ++i )
    {
       file >> array.data[i];
   }
}

int main()
{
     Array array;
     fileToArray("data",array);
     for( int i = 0 ; i < array.size ; ++i )
     {
          std::cout << array[i] << '\n';
     }
}


Better still, you can use std::vector, which is a class designed to
act like a dynamic array.

#include <vector>

// prefer to pass complex types by const reference
int fileToArray(const std::string &filename, std::vector<int> &array)
{
    std::ifstream file(filename.c_str());
    int len;
    file >> len;
    array.resize(len);

    for( int i = 0 ; i < array.length() ; ++i )
    {
       file >> array[i]
   }
}

int main()
{
     std::vector<int> array;
     fileToArray("data",array);
     for( int i = 0 ; i < array.size() ; ++i )
     {
          std::cout << array[i] << '\n';
     }
}

You can still write your own mergesort that uses std::vector (or
better still, generic iterators).

---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html


Other related posts: