can not find dangling pointer in linked list HELP

#include<iostream>
#include<cmath>
#include<string>

using namespace std;

struct listNode {
string word;
listNode*next;
};

int main() {
//just trying omething simple to get the hang out linked list
listNode *boy; //*girl,*temp,*tail;
string word;
cout << "enter word :";
cin >> word;
for (int i = 0; i < word.length(); i++) {
boy = new listNode;
boy->word[i];
cout << boy->word[i] << endl;
boy = boy->next;
if (boy->next == NULL) {
cout << "this is he last letter " << boy->word[i] << endl;

}
}


system("pause");
return 0;
}
1) Please use code tags when posting code, to make it readable:

http://www.cplusplus.com/articles/z13hAqkS/

2) What is the following line supposed to do? Because it actually does nothing at all:

boy->word[i];

3) boy = boy->next;

What do you think the value of boy->next is at this point? What do you think the value of boy will be after this line?
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
#include<iostream>
#include<cmath>
#include<string>

using namespace std;

struct listNode {
	string word;
	listNode*next;
};

int main() {

	listNode *boy; //*girl,*temp,*tail;
	string word;
	cout << "enter word :";
	cin >> word;
	for (int i = 0; i < word.length(); i++) {
		boy = new listNode;
		boy->word[i];//stores the first letter of the word into the node
		cout << boy->word[i] << endl;
		boy = boy->next;//points to the next node
		if (boy->next == NULL) {
			cout << "this is he last letter " << boy->word[i] << endl;

		}
	}
	

	system("pause");
	return 0;
}
Last edited on
boy->word[i];//stores the first letter of the word into the node

No, it doesn't. It does nothing.

Actually, that's not true. It attempts to evaluate data in invalid memory. At this point, there is nothing stored in boy->word, so boy->word[i] is invalid memory. Attempting to access this data will cause undefined behaviour.

But even if there was data there, this statement wouldn't do anything with it. It just means "the ith character in boy->word". It doesn't do anything with that character. It doesn't assign anything to that character, it doesn't do anything else with that character. It's the equivalent of writing:

'a';

as the entire line of code.

boy = boy->next;//points to the next node

That doesn't answer my questions:

What do you think the value of boy->next is at this point? What do you think the value of boy will be after this line?

Think about the first of those questions.
Last edited on
thanks, i figured it out, this stuff is tricky to learn , drawing it out helps allot

Yeah. Often in programming, the trick is to first think about the concepts and work the logic out, before worrying about how to code it.
Topic archived. No new replies allowed.