saving random value from main to a function array

so this is what i'm suppose to do but its got me kinda confused, and my program just crashed 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>
#include <iomanip>
#include <ctime>

using namespace std;

int *MyArray(int);


int main()
{
	srand(time(0));
	int random = rand() % 5 + 1;
	int size = 5;
	MyArray(size);
	int array[] = {random};
	cout << array[1];
}

int *MyArray(int numOfElements)
{
	int *array;
	array = new int[numOfElements];

	return array;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstdlib>
#include <ctime>

int* allocate( int number_of_elements )
{
    if( number_of_elements < 0 ) return nullptr ;
    else return new int[number_of_elements] {} ; // {} => initialise to all zeroes
}

int main()
{
    std::srand( std::time(nullptr) ) ;

    const int n = std::rand() % 5 + 1 ;
    int* array = allocate(n) ;

    array[0] = 987 ;
    std::cout << array[0] << '\n' ;

    delete[] array ;
}
um not sure that really does what i need. thx tho. @JLBorges
Last edited on
Topic archived. No new replies allowed.