-1

my code is here :

#include <iostream>
using namespace std;

struct Mhs
{
int nim;
char nama[10];
Mhs *next;
};

void fs(Mhs *m)
{
m = m->next;
}

int main()
{
int i;
Mhs mhs[2] = { {1, "Alice", &mhs[1]}, {2, "Bob", &mhs[0]} };
Mhs *m = &mhs[0];
fs(m);
for(i = 0; i < 2; i++)
{
   cout << m->nama << ":" << m->nim << " ";
   m = m->next;
}
cout << endl;
return 0;
}

why the output is : Alice:1 Bob:2 but already perform the function fs ()

but, if I remove fs(m); and replace m = m->next; then the output will be like this : Bob:2 Alice:1

What different ???????

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    You are passing the argument *by value*, meaning it is *copied*. Modifying a copy will of course not modify the original. [Find a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and read about *references*. – Some programmer dude Feb 03 '17 at 08:30
  • If i change m = m->next; in fs() function and replace to m->next = m; so the output is : Alice:1 Alice:1 – Danny Purnama Feb 03 '17 at 08:31
  • Emphasizing on @Someprogrammerdude, try `void fs(Mhs*& m).` – A.S.H Feb 03 '17 at 08:33
  • 1
    This is the same behaviour as `void f(int x) { x = 1; }`. There's nothing special about pointers. – molbdnilo Feb 03 '17 at 08:41

2 Answers2

1

void fs(Mhs *m) means you are assigning another pointer to another variable. like for you case

Mhs *m = &mhs[0];
Mhs *m1 = m; // fs(m); <<<<<< 
m1 = m1->next; // <<<<<<<<<
for(i = 0; i < 2; i++)
{
   cout << m->nama << ":" << m->nim << " ";
   m = m->next;
}

will be the same as you code.

Here you are using the same variable for function argument (m), but c++ wise it is different variable.

To have the effect you can do it as below:

void fs(Mhs **m)
{
    *m = (*m)->next;
}

Passing a pointer to a linked list in C++

Community
  • 1
  • 1
Swapnil
  • 1,424
  • 2
  • 19
  • 30
0

please check this code

struct Mhs
{
    int nim;
    char nama[10];
    Mhs *next;
};

void fs(Mhs **m)
{
    *m = (*m)->next;
}

int main()
{
    int i;
    Mhs mhs[2] = { {1, "Alice", &mhs[1]}, {2, "Bob", &mhs[0]} };
    Mhs *m = &mhs[0];
    fs(&m);
    for(i = 0; i < 2; i++)
    {
        cout << m->nama << ":" << m->nim << " ";
        m = m->next;
    }
    cout << endl;
    return 0;
}
  • Okay, you edited it to remove the word "reference", but now the answer is even less useful. Why should I "check" the code? What have you done here? How does it solve the problem? This is just a code dump, not an answer. – Cody Gray - on strike Feb 03 '17 at 11:08