【问题标题】:Pass 3D dynamically allocated array into function (C++) [closed]将 3D 动态分配的数组传递给函数(C++)[关闭]
【发布时间】:2014-01-29 03:34:00
【问题描述】:

我已经动态分配了一个 3D 数组。然后我将字符串分配到数组中。 3D 阵列打印效果很好。但我似乎找不到将它传递给函数的方法。我尝试了许多将数组传递给函数的变体。以下是我的代码,非常感谢您的帮助。

//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;
}

【问题讨论】:

  • 什么问题?我在这里没有看到任何问题。你已经传递给函数了。
  • 我得到一个错误,如果我复制并粘贴错误会有帮助
  • 是的.. 在此处添加您的错误。
  • 错误状态:无法声明指向 'std::string& {aka truct std::basic_string&} 的指针
  • 如果这是 o 任何帮助::: 候选是:模板 typename __gnu_cxx::__enable_if<:__is_char>::__value, std::istreambuf_iterator<_chart2 std ::char_traits> > >::__type std::find(std::istreambuf_iterator<_chart2 std::char_traits> >, std::istreambuf_iterator<_chart2 std::char_traits> >, const _CharT2& ) /usr/include/c++/4.6/bits/stl_algo.h:4394:5: 注意:模板 _IIter std::find(_IIter, _IIter, const _Tp&)

标签: c++ arrays function dynamic-memory-allocation


【解决方案1】:

我不知道问题的具体情况,但是,您是否考虑过为您的 3D 阵列使用类似的东西:

#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

这也带来了一点好处:无需担心释放任何东西。当您的 array3D 变量超出范围时,向量将释放所有内容。 只是另一个你可能会觉得有帮助的想法:)

【讨论】:

    【解决方案2】:

    尝试将重命名函数 findmyfind 之类的其他内容一起使用。

    在和 OP 讨论之后,才知道他错过了声明函数原型。因此更新答案。

    编辑:删除 string.h 包含建议。

    【讨论】:

    • 感谢您的关注,但包括在内
    • 找到了解决方案,你带领我走上了正确的道路,谢谢
    • 你做了什么改变让它工作?
    • 这很愚蠢,但我忘了在 main 上面声明我的函数
    • 好的。所以编译器试图链接find的已知定义,即std::find。很高兴我可以帮助你;)
    猜你喜欢
    • 2016-02-19
    • 2023-04-04
    • 2018-05-02
    • 1970-01-01
    • 2017-04-06
    • 2018-04-23
    • 2010-09-25
    • 2011-03-25
    相关资源
    最近更新 更多