0

I am learning to apply C++ pointers by creating a program that can multiply the combination of numbers from two arrays and pass the list of numbers in a newly created array. But the result produced from the program outputs garbage values in the result, probably a dangling pointer problem.

Here's my code:

#include <iostream>

using namespace std;

void print(int *array[], size_t array_size);
int *apply_all(int array1[], size_t size1, size_t array2[], int size2);


void print(int array[], size_t array_size) {
    cout << "[ ";
    for (size_t i{0}; i < array_size; ++i)
        cout << array[i] << " ";
    cout << "]" << endl;
}

int *apply_all(int array1[], size_t size1, int array2[], int size2) {
    int new_array [size1 * size2] {};
    int *array_ptr {new_array};
    for (size_t i_1{0}; i_1 < size1; ++i_1) {
        for (size_t i_2{0}; i_2 < size2; ++i_2) {
            *array_ptr = array1[i_1]*array2[i_2];
            array_ptr++;
        }
    }
    return array_ptr;
}


int main() {
    const size_t array1_size {5};
    const size_t array2_size {3};

    int array1 [] {1,2,3,4,5};
    int array2 [] {10,20,30};

    cout << "Array 1: ";
    print(array1, array1_size);

    cout << "Array 2: ";
    print(array2, array2_size);

    int *results = apply_all(array1, array1_size, array2, array2_size);
    constexpr size_t results_size {array1_size * array2_size};

    cout << "Result: ";
    print(results, results_size);



}

Output:

Array 1: [ 1 2 3 4 5 ]
Array 2: [ 10 20 30 ]
Result: [ 0 1249712272 500 -353954405 32759 14 0 3 0 5 0 562035404 117 58 0 ]

Do I have to do something with dynamic memory allocation?

  • `new_array` is a local variable. You're returning a pointer to it which is left dangling after the function ends because the local variables are destroyed. – Retired Ninja Jul 28 '22 at 07:31
  • `int new_array [size1 * size2] {};` -- This is not valid C++. [See this](https://godbolt.org/z/aYce1hjfT). Arrays in C++ must have their size denoted by a compile-time value, not a runtime value. Dynamic arrays in C++ are spelled `std::vector new_array(size1 * size2);`. – PaulMcKenzie Jul 28 '22 at 07:37
  • Pointers shouldn't be used in the way you are attempting to use them (very awkwardly and error prone). The `apply_all` could have returned a `std::vector` instead of `int *`. Then inside `apply_all` -- `int *array_ptr = new_array.data();`, given that `new_array` is also a vector. Then a simple `return new_array;` would have worked. – PaulMcKenzie Jul 28 '22 at 07:45
  • [And here is the cleaned up version](https://godbolt.org/z/fabfsa68a). – PaulMcKenzie Jul 28 '22 at 07:49

0 Answers0