c/c++语言开发共享从C ++中的函数返回2d数组

我有一个声明如下的函数:

unsigned char** Classifier::classify(){ //... unsigned char **chars = new unsigned char *[H]; for(int i = 0; i < H; i++) chars[i] = new unsigned char[W*3]; //... return &chars; //note: when this is "return chars;" I get the following: cannot convert 'unsigned char*' to 'unsigned char**' in return 

这给了我警告:

 Classifier.cpp: In member function 'unsigned char** Classifier::classify()': Classifier.cpp:124: warning: address of local variable 'chars' returned 

这可以忽略吗? 基本上,我的问题是如何返回对函数中定义的数组的引用?

我希望能够做到

 unsigned char** someData = classify(); 

    绝不可以忽略。 您将返回本地变量的地址。 当您在调用者有机会使用它之前离开classify()的堆栈帧时,该地址将变为无效。

    您只需要返回该变量的值:

     return chars; 

    只返回数组,而不是它的地址:

     return chars; 

    &chars是指向指针的指针,但是chars是指向指针的指针(你想要的)。 另请注意, chars 不是数组。 指针和数组不是一回事,尽管它们经常混淆。

    @Adam Rosenfield得到了正确的答案,所以有其他一些,(删除那个&符号),但作为思考的食物,一个很好的方法是使用std :: vector(std :: vectors)并将其传递给该函数作为参考参数。

     #include  void Classifier::classify(std::vector> & chars) { //construct a vector of W*3 integers with value 0 //NB ( this gets destroyed when it goes out of scope ) std::vector v(W*3,0); //push a copy of this vector to the one you passed in - H times. for(int i = 0; i < H; i++) chars.push_back(v); } 

    chars填充了你想要的东西,当涉及到删除vector ,你不必担心如何调用正确的delete[]语法,你可以在2D数组中调用new

    您仍然可以像使用2D数组一样引用此向量中的项目,例如chars[5][2]或其他任何内容。

    虽然我可以看到你想要去:

      unsigned char** someData = classify(); 

    因此,如果您想使用向量,则必须按如下方式声明someData:

      std::vector> someData; 

    并且可能更清楚:

     typedef std::vector> vector2D; vector2D someData; classify(someData); ... 

    不,忽视这个警告是不可行的。 您返回的值是堆栈中chars的地址,而不是它指向的chars 。 你想要回归chars

    其他人给出了答案; 但作为一般观察,我建议你看一下STL。 你已经标记了问题C和C ++,所以我假设你在C ++环境中并且STL可用。 然后,您可以使用typedef以可读forms定义向量,甚至使用向量向量(即2d数组)。 然后,您可以将指针或引用(视情况而定)返回到向量向量。

      以上就是c/c++开发分享从C ++中的函数返回2d数组相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/544888.html

      (0)
      上一篇 2021年1月9日
      下一篇 2021年1月9日

      精彩推荐