returning structure

I am having a problem returning pigLatin.piglatin;... i can not see the problem, anyone else see it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;

struct Word
	{
		string piglatin;
		string english;
	};

Word piglatin(string latin, int &size);

int main() {

int sum=1; // how many words

string pig;

Word latinReturn; // the return from function;

cout <<"Enter a sentence in piglatin to decode";
getline(cin,pig); // get user input

latinReturn = piglatin(pig,sum); // call to function piglatin

	return 0;
}




Word piglatin(string latin, int &size){

	for (int i=0; latin.length() > i; i++)
	{
	if(latin[i] == ' ')
		{
		size++;
		}
	}
		int x=latin.length();
		string temp;
		char ending = latin[x-1];

			for(int i=0;i <latin.length(); i++)
			{
				latin[i] = tolower(latin[i]);
			}

			for(int i=0; i < latin.length(); i++)
			{
				if(isalpha(latin[i]) || isspace(latin[i]))
				{
					temp += latin[i];
				}
			}
			latin =temp;
			latin +=ending;

			Word pigLatin;

			for(int i=0; i<latin.length(); i++)
			{
				pigLatin.piglatin[i] = latin[i];
			}

		cout << pigLatin.piglatin[1];

	return pigLatin;
}

$ g++ foo.cpp -ggdb -D_GLIBCXX_DEBUG
$ gdb a.out
> run
Enter a sentence in piglatin to decode hola mundo feliz

(...): Assertion '__pos <= size()' failed.
Program received signal SIGABRT, Aborted.
> backtrace
(...)
#4  0x0000000000402135 in piglatin (latin="hola mundo felizz", size=@0x7fffffffdf8c: 3) at foo.cpp:66
#5  0x0000000000401e57 in main () at foo.cpp:27
> frame 4
> list
62              Word pigLatin;
63
64              for (int i = 0; i < latin.length (); i++)
65              {
66                      pigLatin.piglatin[i] = latin[i];
67              }
`pigLatin.piglatin' is an empty string, yet you try to access it from [0: latin.lengh()]
An out of bounds access will not make the string bigger, it is undefined behaviour.

You may simply do pigLatin.piglatin = latin;
Topic archived. No new replies allowed.