Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return 2d array from function in C++

I have a function declared like so:

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

This is giving me the warning:

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

Is this ok to ignore? Basically, my question is how do you return a reference to an array that is defined in the function?

I want to be able to do

unsigned char** someData = classify();
like image 507
Derek Avatar asked Dec 03 '22 09:12

Derek


2 Answers

Just return the array, not its address:

return chars;

&chars is a pointer to a pointer to a pointer, but chars is a pointer to a pointer (what you want). Also note that chars is not an array. Pointers and arrays are not the same thing, although they are often confused.

like image 97
Adam Rosenfield Avatar answered Dec 31 '22 15:12

Adam Rosenfield


This is never okay to ignore. You're returning the address of a local variable. That address will become invalid when you leave classify()'s stack frame, before the caller has a chance to use it.

You only need to return the value of that variable instead:

return chars;
like image 22
Frédéric Hamidi Avatar answered Dec 31 '22 14:12

Frédéric Hamidi