从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); ... 
  1. 如果在函数中定义了一个数组,并且你想在函数外部使用它 – 你应该将它(数组)描述为静态或在函数外声明一个数组并将其作为参数传递。

  2. 使用“return chars;” 只要;

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

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