C++ Dynamic Arrays Creation

I am prompted with the question as follows

  1. Write a program that prints dynamic arrays.
  2. The program creates an int 1D dynamic array of 3 elements and a float 2D dynamic array of 3 ROWS and 3 COLS.
  3. Initialize both arrays with random values.
  4. Both arrays will be printed separately in two separate functions
  5. void print_2d_array(float**);
  6. void print_1d_array(int*);”

I have created a code that will not produce any output. I am guessing the issue is in the initialization of the arrays, but I cannot figure it out. How do I get it to display the randomly generated numbers?

#include <iostream>
#include <iomanip>

using namespace std;

void print_2d_array(float**);
void print_1d_array(int*);

int main() {
    srand(time(NULL));

    int* arr[3];
    float** arr_two[3][3];

    for (int i = 0; i < 3; i++)
        *arr[i] = rand() % 100;
    
    for (int j = 0; j < 3; j++)
        for (int k = 0; k < 3; k++)
            **arr_two[j][k] = rand() % 100;

    print_1d_array(*arr);
    print_2d_array(**arr_two);
}

void print_2d_array(float** arr_two) {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++)
            cout << arr_two[i][j];
    }
    cout << endl;
}

void print_1d_array(int* arr) {
    for (int i = 0; i < 3; i++)
        cout << arr[i];
}

Answer

You never allocate memory for the 1D int array, nor for the float 2D array. Your declarations are also wrong, for example float** arr_two[3][3] is an array of size 3 of arrays of size 3 of pointers to pointer to float, clearly not what you want.

Your code should look more like this:

int *arr = new int[3]; // pointer to int will hold 3 ints

float **arr_two = new float *[3]; // array of 3 pointers to float

for (int i = 0; i < 3; i++)
{
    arr_two[i] = new float[3]; // each pointer will hold 3 floats
}

for (int i = 0; i < 3; i++)
    arr[i] = rand() % 100; // indexing is the same as if it was an array[size]

for (int j = 0; j < 3; j++) // indexing is the same as if it was an array[size][size]
    for (int k = 0; k < 3; k++)
        arr_two[j][k] = rand() % 100;

print_1d_array(arr); // you pass the name of the pointers, no dereference needed
print_2d_array(arr_two);

You should also print some spaces and newlines in your print functions, otherwise this will look like a very large single value.

Also, don’t forget to free the memory later, when you no longer need the data:

delete[] arr;

for (int i = 0; i < 3; i++)
{
    delete[] arr_two[i];
}

delete[] arr_two;

I should also mention that in modern C++ very rarely we see the usage of raw pointers (except maybe in SO questions). Alternatives are:

Also note that your random values are all int, so you won’t see float values in the float arrays. If you want randomly generate fractional values, you need a new approach, take a look here: Random float number generation