1

I am now starting Dynamic Memory Allocation in class and have a ok understanding of it but can't completely use it properly. I feel like I may not be so great with pointers either :p

My instructor gave instructions to create a function named readArray that will prompt the user for a number to use as a size to dynamically create a integer array of that size. I am then to assign the new array to a pointer. I then am supposed to prompt the user to fill the array. I then am supposed to return both the newly created array and the size.

I can not figure out how to return the array though, and I thought when dynamically allocating memory you were supposed to delete the allocation after using it to prevent leaks.

The array and size must be returned to main so I can pass it to other functions such as a sorting function.

I would greatly appreciate any help I can get as my thought process with this keeps going in the wrong direction.

#include <iostream>
using namespace std;

int* readArray(int&);
void sortArray(int *, const int * );

int main ()
{
   int size = 0;
   int *arrPTR = readArray(size);
   const int *sizePTR = &size;
   sortArray(arrPTR, sizePTR);

   cout<<arrPTR[1]<<arrPTR[2]<<arrPTR[3]<<arrPTR[4];

        system("pause");
        return 0;
}


int* readArray(int &size)
{
   cout<<"Enter a number for size of array.\n";
   cin>>size;
   arrPTR = new int[size];

   for(int count = 0; count < (size-1); count++)
   {    
       cout<<"Enter positive numbers to completely fill the array.\n";
       cin>>*(arrPTR+count);
   }

   return arrPTR;
}
3
  • Slight mistake in your example that the prototype of readArray differs from what you have implemented. Although it is not necessary you might also consider giving variable names in the prototypes to aid in documenting what they do. Commented Feb 16, 2012 at 15:46
  • 1
    You generally don't want to change your example code to match the solution. That is what the answers are for (which then might make no sense when you make updates like this). Commented Feb 16, 2012 at 15:48
  • 1
    Although most classes on C++ probably cover raw arrays like this pretty early I think it's a bad idea. Beginners should be taught to use vectors, leaving raw arrays and manual dynamic allocation to later in the course as an advanced topic. This is the way Bjarne Stroustrup's wonderful beginner's book Programming—Principals and Practice Using C++ handles it. Commented Feb 16, 2012 at 15:57

3 Answers 3

6

You would not need to do that if you use std::vector<int> which is far superior choice.

Use it:

std::vector<int> readArray()
{
    int size = 0;
    cout<<"Enter a number for size of array.\n";
    cin >> size;
    std::vector<int> v(size);

    cout<<"Enter "<< size <<" positive numbers to completely fill the array : ";
    for(int i = 0; i < size; i++)
    {   
        cin>> v[i];
    }
    return v;
}
Sign up to request clarification or add additional context in comments.

17 Comments

This would be the perfect solution but it seems they should study new operator usage right now, mentioning vectors (and other containers) may be confusing. IMHO.
I haven't learned about vectors yet and the assignment is very specific on using pointers and the new operator.
@Vyktor: A C++11 compiler will return the vector by moving it; a decent C++03 compiler will elide the copy.
This is the way C++ courses should be taught. Although most classes on C++ probably cover raw arrays like this pretty early it's a mistake. Beginners should be taught to use vectors, treating raw arrays and manual dynamic allocation as an advanced topic. Bjarne Stroustrup's beginner's book Programming—Principals and Practice Using C++ does this correctly.
@bames53: I disagree. In university, the goal of teaching basics c++ is not only "to use c++ properly". One of the goals of these courses is also that the students will understand memory allocations [automatic/dynamic], the difference between reference variables and value variables, memory layout, .... Understanding those concepts usually require some dirty work with dynamic array allocations and using pointers [to pointers to pointers...]
|
5

To return an array: declare readArray() as int* readArray() [return an int* instead of an int], and return arrPTR instead of size. This way, you return the dynamically allocated array which arrPTR points to.

Regarding the delete: When you are done using the array, you should indeed delete it. In your example, do it before return 0 in your main() function.
Make sure that since you allocated memory with new[], you should also free it with delete[], otherwise - your program will have a memory leak.

5 Comments

Make sure it is deleted using delete []
@Vyktor: This is homework, I only gave him hints how to do it, if I do what you are suggesting, he will not learn from it.
@Joe: you are 100% correct. What seems trivial to us, is not for beginners. I will edit my answer and add it.
@amit I have done what you said and edited my code up top but I still am having problems. on int *arrPTR = readArray(size); readArray has the error "more than one instance of overloaded function "readArray" matches the argument list."
Nevermind I forgot a reference variable in my function declaration :p
1

Like amit says, you should probably return the array instead of size. But since you still need the size, change readArray like so:

///return array (must be deleted after)
///and pass size by reference so it can be changed by the function
int* readArray(int &size);

and call it like this:

int size = 0;
int *arrPTR = readArray(size);
///....Do stuff here with arrPTR
delete arrPTR[];

After update:

int* readArray(int size); ///input only! need the & in the declaration to match
                          ///the function body!

Is wrong, since you have your actual definition with the int &size. You also don't declare arrPTR in readArray, just assign it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.