1

I'm trying to recursively call a function with a 2d array as an argument.

My compile error is

knapsack.cpp:76:55: error: cannot convert ‘int (*)[(((sizetype)(((ssizetype)(knapsack_capacity + 1)) + -1)) + 1)]’ to ‘int**’ for argument ‘1’ to ‘void backtrack(int**, int, int, std::vector)’ backtrack(T, items_amount, knapsack_capacity, weights);

My function is declared like this:

void backtrack (int **T, int item, int weight, vector<int> weights)
{
        if (T[item][weight] == T[item-1][weight]) {
                cout << item << ", ";
                backtrack(T, item-1, weight-weights[item-1], weights);
        }
        else if (item <= 0 && weight <= 0) {
                // Dont do anything
        }
        else {
                backtrack(T, item-1, weight, weights);
        }
}

And being called like this:

backtrack(T, items_amount, knapsack_capacity, weights);

I looked in a million different ways of combining [] and *, but no success. Any ideas?

1 Answer 1

2

You are probably passing an array, like int arr[10][20]; to your function. Such an array does not decay to int**, but to int (*)[20] (i.e., pointer to array-of-20-int) . So, either change your function signature so that you specify the second dimension, or, instead of passing an array int[10][20], pass a pointer-to-pointer int** (for which you have to allocate memory etc). Example of using both approaches:

#include <cstddef>

void f(int (*arr)[20]){}
void g(int**){}

int main()
{
    // using a pointer to array-of-20-ints
    int arr[10][20];
    f(arr);

    // 10 x 20 dynamic array, allocate
    int** ptr = new int*[10]; // allocate memory for the pointers to rows
    for(std::size_t i = 0; i < 10; ++i)
        ptr[i] = new int[20]; // allocate each row

    // process
    g(ptr);

    // deallocate
    for(std::size_t i = 0; i < 10; ++i)
        delete[] ptr[i]; // delete each row
    delete[] ptr; // delete the memory allocated for the pointers to the rows
}

But, really, you should use a std::vector<std::vector<int>> instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.