Ryan Newman
Ryan Newman

Reputation: 856

Returning struct array in c++

I am trying to return a array of structs in my class but I keep getting an 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 return in my .cpp file

My class declaration is:

enum arrow {UP, LEFT, DIAGONAL};

struct cellValue
{
    int stringLenght;
    arrow direction;
};

class LCS
{
public:
    cellValue LcsLength (string, string);
};

And when I try returning in my function I have:

cellValue LCS::LcsLength (string X, string Y)
{
    cellValue table[1024][1024];

    return table;
}

Upvotes: 3

Views: 836

Answers (2)

legends2k
legends2k

Reputation: 32884

cellValue LCS::LcsLength (string X, string Y)
{
    cellValue table[1024][1024];

    return table;
}

The problem here is in understanding that the local array table would decay into cellValue(*)[1024] and not cellValue which is what the function's return type is, as per the definition.

Another issue is, even if you fix the type issue, you'd be returning a local variable's pointer, which would be destroyed when the function goes out of scope and the callee would end up with a dangling pointer i.e. pointer to a loction no longer under your control.

You should go with std::array if you must return a collection of objects whose size required is known at compile-time, else go with Tartan's suggestion of using std::vector. You wouldn't be incurring any hit in performance too with C++11's guarentees.

Upvotes: 2

TartanLlama
TartanLlama

Reputation: 65600

You have two main issues with your LcsLength function: your return type is wrong and you have a dangling pointer.

You declare LcsLength as returning a cellValue object, but then try and return a cellValue[1024][1024]. This is why you are getting your compiler error.

Regardless of the return type, what you are doing will not work, as table will be destroyed as soon as the function exits. You would be much better off using std::vector, or maybe std::map depending on what that table is for.

Upvotes: 8

Related Questions