C ++ what is the difference between usage. or & # 8594; for linked list

Suppose I have a structure.

struct node {
 string info;
 node link*;

}

What's the difference between

node k;
node b;

k.info = "string";
b.info = "string";
k.link = &b;

and

node *k;
node *b;
k = new node;
b = new node;    
k->info = "string";
b->info = "string";
k->link = b;

in terms of memory allocation? Are both examples correct and create an appropriate linked list? Added: Most books use a second example, why? Is there a downside to using the first example?

+3
source share
9 answers

Yes. both are technically correct.

In the first example, the memory is on the stack, the second is on the heap.

, "" ( ). , , . , , b , k , k , undefined ( ).

, , , . , , . . .

+6

, ( , , ), - ( new delete ).

, , ( ) .

+2

.

  • . ,
  • -> ,

node k, *m, *n;

m = &k;
n = new node;

k.info  = "Hello";   // k is a node type object so use directly . operator
m->info = "Hi";      // m is a pointer to an object to type node, so use -> operator
n->info = "Man";     // n is a pointer to an object to type node, so use -> operator
*(m).info = "This";  // *(m) refers to an object itself, we use . operator on it
*(n).info = "Is a test"; // *(n) refers to an object itself, we use . opeartor on it

  • node k; ,
  • static node k; node k; , .data
  • new ,

, , , node . , . . , node *k; k = new node;, node, k->info;, . , -> /, , . .

PS. delete ( new) , .

+2

, .

, . .

, "". , , , .

+1

.

: -, , .. . -, , .

: ( new, malloc() ..) (delete, free()), :

  • ( ex: , ). , . , , .

  • . .

, ( ).

+1

, , , . , , - . : ( ) , , . , ( ). , - , , , , . , .

+1

. . ->. . . . .

0

→ . : , List, getRoot(), Nodes. getNext(), node .

*List myList;

Suppose we know that myList is a 5-node list. The list and 5 nodes are located on the heap (dynamically allocated). Now we want to access the last node.

myList->getRoot()->getNext()->getNext()->getNext()->getRoot();
(*(*(*(*(*myList).geRoot() ).getNext()).getNext()).getNext()).getNext();

These two sentences are equivalent and will return the fifth and last node. For the convenience of the programmer, use the first one.

0
source

All Articles