Returning a struct array in C ++
I am trying to return an array of structures in my class, but I keep getting the error
error C2556: 'cellValue *LCS::LcsLength(std::string,std::string)' : overloaded function differs only by return type from 'cellValue LCS::LcsLength(std::string,std::string)'
when i go back to my .cpp file
My class declaration:
enum arrow {UP, LEFT, DIAGONAL};
struct cellValue
{
int stringLenght;
arrow direction;
};
class LCS
{
public:
cellValue LcsLength (string, string);
};
And when I try to return to my function, I have:
cellValue LCS::LcsLength (string X, string Y)
{
cellValue table[1024][1024];
return table;
}
source to share
You have two main problems with your function LcsLength
: your return type is wrong, and you have a dangling pointer.
Declare LcsLength
as a returning object cellValue
, but then try and return cellValue[1024][1024]
. This is why you are getting a compiler error.
Regardless of the return type, what you do won't work as it table
will be destroyed as soon as the function exits. You will be much better off using std::vector
or perhaps std::map
depending on what this table is for.
source to share
cellValue LCS::LcsLength (string X, string Y)
{
cellValue table[1024][1024];
return table;
}
The problem is in understanding what the local array table
decays to cellValue(*)[1024]
, not cellValue
what is the return type of the function as defined.
Another problem is that even if you fix the type problem, you will return a local variable pointer, which will be destroyed when the function goes out of scope and the called party will have a dangling pointer, meaning the pointer to loction is no longer located under your control.
You have to go with std::array
if you have to return a collection of objects the size of which is required at compile time, then go with Tartan's suggestion for use std::vector
. You won't have any performance hit with C ++ 11 guarentees.
source to share