linked list question

Hi,

I have a class that looks like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class A {
 int count;
 A *next;
}

class B {
 int num;
 A *head;
}

void B::add(A a) {
 A *pt = head;
 if (pt == NULL) {
  pt = a;
 } else {
  while (pt != NULL) {
   pt = pt->next; 
  }
  pt->next = a;
 }
 num++;
}


I tried to assign pt = a, but kept getting "cannot convert A to A*". I understand I am converting a A pointer to A, but *pt = A or pt = &A both gave me seg fault, why is that?

TIA

R
I am very new myself to C++, but hopefully you will find this helpful (and accurate):

pt = &a; // that should work
pt is a pointer to an object of type A,
&a is the address of an object of type A.
After that line of code pt and &a reference the same value (ie. contain the same address).
Also, after, *pt and "a" are exactly the same value (ie. same address references the same value).

You say you tried "pt = &A", and if you really capitalized the "A", then that is the problem,
but I would have expected a compile time error rather than the seg fault you described.

For the other option you tried:
1
2
3
4
*pt = a;    
// I would expect a seg fault here, 
// because *pt has not been allocated memory to store a value (no space for a copy of a)
// p. 149 of C++ Primer Plus (Stephen Prata) explains this. 


closed account (D80DSL3A)
You will still have a problem with line 14 as pt = &a; because a is passed by value. A copy of a is made for the function to use which goes out of scope when the function ends.
Pass a reference to a instead: void B::add(A& a).This way pt is assigned the address of the variable being passed instead of the address of the local copy of a.
Also, I think line 19 needs to be pt->next = &a; as next is a pointer.
After playing with it some more, I found out what the issue was. Just like what fun2code said, The problem is inside

 
void B::add(A a) {


I should pass a in as a pointer, not a value. So, I have modified it to be

1
2
void B::add(A * a)


The caller does something like
1
2
3
4
5
6
7
8
9
10
11

A *a = new A();

// rather than

A a;

// and call it like

B.add(a);


Thank you so much!!


Topic archived. No new replies allowed.