1

My teacher setup some skeleton code for an assignment on linked lists.

In the header, two classes are defined: string_node and string

In the string definition, there is a private variable mutable string_node* cursor;

Now in the actual implementation, I'm trying to use cursor as the reference to the nodes I create and want to modify. IE:

for (cursor_index = 0; cursor_index < many_nodes; cursor_index++){
        cursor = new string_node(str[cursor_index]);

I'm not sure if this is proper so first of all, could anybody tell me how I'm supposed to do it if this is wrong?

I assume its wrong because I can't access the node's data and links to other nodes via cursor since its a pointer (I'd like to be able to just do cursor.data or even setup get and set methods although I'm not sure why I would need to, if somebody would like to explain that to me).

So the main issue is being able to set the node's data/links in the implementation.

AMadmanTriumphs
  • 4,888
  • 3
  • 28
  • 44
Jarryd Goodman
  • 477
  • 3
  • 9
  • 19

2 Answers2

1

There are two ways to get things out of pointers.

The first is to dereference it:

string_node &mynode = *cursor;
mynode.whatever;

The second (much better way) is to use the dereferencing operator (which does the same but is more elegant):

cursor->whatever;

Moving on to your method: maybe my answer to a related question will help you: How to point an array inside a dynamic array to something?

You might also get some help from Wikipedia's pseudo-code: http://en.wikipedia.org/wiki/Linked_list#Linked_list_operations

Community
  • 1
  • 1
Dave
  • 44,275
  • 12
  • 65
  • 105
  • Thanks. I had to use *cursor-> but aside from that it's all good. – Jarryd Goodman Mar 05 '13 at 20:39
  • *cursor->whatever; means something else: get "whatever" from cursor, then dereference the result. You should be careful; it sounds like you're getting muddled up with the structure of what you're trying to do. – Dave Mar 05 '13 at 20:42
  • Well it was giving me an error with cursor-> so I put the asterix but now it had me change it back. Curious. – Jarryd Goodman Mar 05 '13 at 20:42
  • I don't think anybody will be able to help your further without more context. You should update your question with more code, such as what your structs look like and what you're actually trying to do. – Dave Mar 05 '13 at 20:44
  • Thanks for the tip Dave I'm a novice for sure. – Jarryd Goodman Mar 05 '13 at 22:46
0

To answer your initial question: you want the "->" operator. It's the equivalent to the "." operator for pointers to an object.

static_rtti
  • 53,760
  • 47
  • 136
  • 192