I'm starting to learn C++ - in particular pointers. I thought I would attempt a basic linked-list. Here's my code:
#include <iostream>
using namespace std;
struct Linked {
Linked *next;
string val;
};
Linked newLinked(string val);
Linked addLinked(Linked l, string val);
void printLinked(Linked l);
Linked newLinked(string val) {
Linked l;
l.val = val;
l.next = NULL;
return l;
}
Linked addLinked(Linked l, string val) {
Linked n = newLinked(val);
n.next = &l;
return n;
}
void printLinked(Linked l) {
Linked *r = &l;
while (r != NULL) {
cout << (*r).val << endl;
r = (*r).next;
}
}
int main() {
Linked list = newLinked("This is the root node.");
list = addLinked(list, "This is the second node.");
list = addLinked(list, "This is the third node.");
list = addLinked(list, "This is the fourth, and final, node.");
printLinked(list);
return 0;
}
Sorry if my formatting is horrible or I'm breaking convention, still learning those. (If you wish please go ahead and point out how I can improve my codestyle, I am coming from a Java/JS background!)
When running, I get this:
This is the fourth, and final, node.
�;��R�;��R
This is the fourth, and
�;��R�;��R
My guess here is that the memory which contains the earlier strings is being overwritten -- the length of "This is the fourth, and " is the same as "This is the second node.".
Unfortunately I am stumped as to why this is... I am hoping someone here may be able to point me (haha) in the right direction.