Question

I have dynamically allocated a 3D array. I then assigned strings into the array. The 3D array prints out fine. But I cannot seem to find a way to pass it to a function. I have tried many variations of passing the array into the function. Below is my code, very grateful for any help.

//dynamically allocate 3d array
string *** array3D;
array3D = new string**[rows];
for(int i = 0; i < rows; i++)
{
    array3D[i] = new string*[columns];
    for(int j=0; j < columns;j++)
    {
        array3D[i][j] = new string[pages];
    }
}

//put strings from file into array
for(int k = 0; k < pages; k++)
{
    for(int i = 0; i < rows; i++)
    {
        for(int j=0; j < columns;j++)
        {
            puzzleFile >> array3D[i][j][k];
        }
    }
}

// Call function
find(array3D);

// The couts are simply to verify the array passed in successfully
void find(string ***&array)
{
    cout << "in function array[0][0][0]" << array[0][0][0] << endl;
    cout << "array[1][0][2]" << array[1][0][2] << endl;
    cout << "array[1][0][2]" << array[0][2][1] << endl;
    return;
}
Was it helpful?

Solution 2

Try to use rename function find with something else like myfind.

After discussing with OP, came to know he missed to declare function prototype. Hence updating answer.

Edit: Removed string.h include suggestion.

OTHER TIPS

I dont know the specifics of the problem, but, did you consider using something like this for your 3D array:

#include <vector>
#include <string>
....
typedef std::vector<std::string>> V1d;  // define a vector of strings: 'pages'
typedef std::vector<V1d> V2d;  // define a vector of V1d: 'columns' of 'pages'
typedef std::vector<V2d> V3dS; // define a vector of V2d: 'rows' of 'columns' of 'pages'
...
void find(V3dS &a3d) {
    // access the data here as a3d[i][j][k] per page
}
...
V3dS array3D(rows, V2d(columns, V1d(pages)));  // declare your array with wanted sizes
...
puzzlefile >> array3D[i][j][k]; // Page data
...
find(array3D);  // call your function

This also comes with a little benefit: no need to worry about deallocating anything. The vectors will free everything when your array3D variable goes out of scope. Just another idea you might find helpful :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top