Need help please, Traversing a linked list.

Hi,
first of all im no expert, so i have been trying to create a linked list of "Minions" where each has x coordinates, y coordinates, wp (weapon power), and a pointer to next minion.

the code:


#include<cstddef>
#include<iostream>
using namespace std;

struct minion{
int x;
int y;
int wp;
minion* next;
};

minion* addnewmin(minion*);

int main()
{
minion* head=NULL;

minion* min1=new minion;
min1=addnewmin(head);

minion* min2=new minion;
min2=addnewmin(head);

minion* min3=new minion;
min3=addnewmin(head);

minion* min4=new minion;
min4=addnewmin(head);

for(minion* i=min4 ; i != NULL ; i=i->next)
cout<<i->wp<<endl;

for(minion* i=min4 ; i != NULL ; i=i->next)
i->wp+=20;

for(minion* i=min4 ; i != NULL ; i=i->next)
cout<<i->wp<<endl;
}

minion* addnewmin(minion* head)
{
minion* port=new minion;
port->x=0;
port->y=0;
port->wp=10;
port->next=head;
head=port;
return port;
}


Problem is:
i made 3 for loops in main, first one to display the current weapon power which expected to output 10 10 10 (initial set weapon powers), 2nd for loop increases their weapon power (for whatever reason, a level up or something), third loop should display the new increased weapon power.
BUT, what i get is 10 and below it 30. looks like min4's wp only increased. There must be something wrong i am doing while i try to loop through my linked list and i cant figure it out... hope someone can help, and sorry for the long story :)
A pointer is a variable.

Here is analogous situation:
1
2
3
4
5
6
7
8
9
10
void foo( int x ) {
 x = 42;
}

int main() {
  int bar = 7;
  foo( bar );
  // What is the value of bar here?
  return 0;
}

That is the familiar by value parameter case. The bar remains 7, because only the value of bar is copied to x on call of foo.

But pointer ... you say. Exactly same by value copy. Your main has "head" and it contains an address (null). That value (address) is copied to variable "head" of the addnewmin.

If the addnewmin would dereference the pointer head, it would access the object at the address. That same object is pointed to by the head of main. (Of cource, here the address is null and there is no object.)

You need to pass a reference, if you want to modify a variable of the caller:
minion* addnewmin( minion* & );
In addition to what Keskiverto said:
1
2
minion* min1=new minion;
min1=addnewmin(head);

Line 1 creates a new minion and points min1 to it.
Line 2 calls addnewmin() and replaces the value of min1 with the value returned by addnewmin. As a result, the minion created at line 1 gets leaked.

Shouldn't addnewmin() take as a parameter the minion to add to the list?
ohh it worked now by adding the reference, i though passing a pointer to a function is a pass by reference by default just like passing an array for example. That cleared many things. Thanks alot for your help ! :)
Topic archived. No new replies allowed.