Home > Software engineering >  How to dynamically create and populate an array of size n?
How to dynamically create and populate an array of size n?

Time:10-27

I am trying to populate an array with varying sizes (ex: A[100], A[1000], etc) with randomly generated numbers. Within the problem statement, vectors are not allowed to solve the problem. These arrays are being generated outside of main and their size, which is given by user input, is being passed as a parameter to the function. I can not figure out how to generate these arrays without hard coding in the array sizes and setting multiple different arrays. What is the best way to generate arrays in this manner, without using vectors?

int size;

cout << "What is the array size? ";
cin >> size;

for (int i = 0; i < size   1; i  ) {
    srand(time(0));
        A[i] = rand() % size;
}

Here I ask for the desired array size and run a for loop to step through the size of the array and set each element in the array with a randomly generated number.

int randNumArray(n) {
    int A[n];

    for (int i = 0; i < size 1; i  ) {
        srand(time(0));
        A[i] = rand() % size;
        
    }

    return A;
}

This is the function I also tried to implement to set the elements of an array of size n with randomly generated numbers. The parameter n was initialized in main with the users input and was then passed to this function.

CodePudding user response:

Creating an array of an undefined size is incorrect because, in c , an array is initialized in compile time. When the program compiles the user has not provided the value for n, therefore int A[n]; is incorrect.

To dynamically create an array of size n you must use the new keyword. The new keyword performs a memory allocation on the heap, making arr a pointer to the allocated memory. Since objects are created at run-time, int* arr = new int[n]; allocates memory of the inputted size n and returns a pointer to the array.

The populate function can then be called on the array's address. This means that the populate function does not have to return anything because it is directly modifying the array's data in the heap. It takes in the address and size of the array and modifies it directly.

When you are done using the array you must free it using delete [] arr;. This will guarentee that your program will free the memory when the program terminates.

void populate(int a[], int size) {
    srand(time(0));
    for(int i = 0; i < size; i  ) {
        a[i] = rand() % size;
    }
}

int main() {
    int n;
    cout << "Enter array size: ";
    cin >> n;
    int* arr = new int[n];

    populate(arr, n);   // populates array with random numbers

    cout << "Listing elements: " << endl;
    for(int i = 0; i < n; i  ) {
        cout << arr[i] << endl;
    }
    delete [] arr;
}
  • Related