Reputation: 3
so this is what i'm suppose to do but its got me kinda confused, this is what i got so far any help would be appreciated:)
Write a function that dynamically allocates an array of integers. The function should accept an integer argument indicating the number of elements to allocate and should return a pointer to the array. Then write a driver in the main function that generates a random number (something not too large), calls the function, and verifies access by saving a value to the first element and displaying the contents of that element.
edited code it runs but i feel like im not using my function at all.
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int *MyArray(int);
int main()
{
srand(time(0));
int random = rand() % 5 + 1;
const int size = 5;
int array[size];
MyArray(size);
array[0] = random;
cout << array[0] << endl;
}
int *MyArray(int numOfElements)
{
int *array;
array = new int[numOfElements];
return array;
}
edited code
int main()
{
srand(time(0));
int random = rand() % 5 + 1;
const int size = 5;
int* array = MyArray(size);
array[0] = random;
cout << array[0] << endl;
delete [] array;
}
Upvotes: 0
Views: 390
Reputation: 2272
I believe you try to do something like this:
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int *MyArray(int);
int main()
{
srand(time(0));
int random = rand() % 5 + 1;
int *array = MyArray(random); //! store the pointer of dynamically allocated memory and use it.
array[0] = random;
cout << array[0] << endl;
delete [] array; //! To avoid memory leak
}
int *MyArray(int numOfElements)
{
int *array = new int[numOfElements];
return array;
}
Note: I'm just guessing this is what you probably looking for.
Upvotes: 2