Tom
Tom

Reputation: 543

c++ returning a custom struct type - error

I have started learning C++ today and am currently having some problems.

I have a custom struct that I called data:

struct data{
int x, y, l;
};

It a simply struct with 3 variables.

Next I run this recursive function. Albeit, it done not matter what it does since printing out the final return statements yields the correct result.

data finds(int x, int y, int length, string s){
    //cout << length << endl;
    int nx = prev(x, s);
    int ny = next(y, s);
    if(nx != -1 && ny != -1 && s.at(nx) == s.at(ny)){
        finds(nx, ny, length + 2, s);
    }
    else{

        cout << x << y << length << endl;
        data vals;
        vals.x = x;
         vals.y = y;
         vals.l = length;
        return vals;
    }
}

The cout statement in this function yields

068

which are the numbers I want. However, when I try to print the results of this functions like so:

464078426865241

which is obviously wrong.

My question becomes: how do I properly return a struct to yield the correct values.

Also you probably want some runnable code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct data{
    int x, y, l;
};
int next(int i, string s){
    //cout << s;
        //cout << j;
    for(int j = i + 1; j < s.size(); j++){
        if(isalnum(s.at(j))){
            return j;
        }
    }
    return -1;
}

int prev(int i, string s){
    //cout << s;
    for(int j = i - 1; j >= 0; j--){
        //cout << j;
        if(isalnum(s.at(j))){
            return j;
        }
    }
    return -1;
}
data finds(int x, int y, int length, string s){
    //cout << length << endl;
    int nx = prev(x, s);
    int ny = next(y, s);
    if(nx != -1 && ny != -1 && s.at(nx) == s.at(ny)){
        finds(nx, ny, length + 2, s);
    }
    else{

        cout << x << y << length << endl;
        data vals;
        vals.x = x;
         vals.y = y;
         vals.l = length;
        return vals;
    }
}

int main(){
    s = "1233321";
    data val;
    val = finds(3, 3, 2, s);

    cout << val.x << val.y << val.l;





}

Upvotes: 0

Views: 267

Answers (1)

David G
David G

Reputation: 96810

You forgot to return the function that did the recursion:

return finds(nx, ny, length + 2, s);
^^^^

Otherwise not doing so results in undefined behavior.

Upvotes: 1

Related Questions