Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i want to implement something like this

C++
#include "StdAfx.h"
#include<iomanip>
#include <iostream>

using namespace std;

class node
{
	int data;
public:
	node *next;
	node(int d);
};
node::node(int d)
{
	data=d;
}

class Linklist
{
	node *start;
	node *next;
public:
	Linklist();
	void append(int d);
};
Linklist::Linklist()
{
	start=NULL;
}
void Linklist::append(int d)
{
	node *ptr=new node(d);
	ptr->next=NULL;
	start=ptr;
}
int main()
{
	Linklist l;
	l.append(10);
	l.append(20);
	return 0;
}

the pointer ptr at append() is assigned to same address every time , why? and what to do to solve it?
Posted
Updated 6-Jul-13 8:27am
v3
Comments
Richard MacCutchan 6-Jul-13 13:21pm    
It's a bit of a jumble of random code; you should try writing out exactly what each part should do before you start coding. And make use of the proper syntax for using pointers.
Richard MacCutchan 7-Jul-13 4:09am    
Your append() function destroys the previous contents of start instead of linking the new node into the chain. Try my previous comment and think more carefully about the logic of each step. Try drawing a picture of a linked list with three or four elements and see how they should be connected, and how that can be achieved with pointers.

1 solution

First big design mistake I can see is: remove all I/O from all class members, otherwise, what are you creating, a class which can only work with cin and cout, nothing else?

[EDIT]

As to your question: ptr1 does not have to be assigned to the same address, as it is assigned to a freshly allocated memory location. It can be the case if you repeat allocation and deletion several times, so next allocation simply takes the piece of memory you just deallocated. It's not clear why do you do it in your code. You should review it.


—SA
 
Share this answer
 
v2
Comments
bhawin parkeria 6-Jul-13 13:31pm    
thanks a lot i will edit this soon
Sergey Alexandrovich Kryukov 6-Jul-13 13:42pm    
Very good.
—SA
bhawin parkeria 6-Jul-13 14:05pm    
@Sergey :- i have edited the question, now i debugged it and found that ptr has same address everytime.
Sergey Alexandrovich Kryukov 6-Jul-13 15:23pm    
All right, I here you. By why doing so? I already explained why it happens...
—SA
bhawin parkeria 7-Jul-13 7:42am    
i am confused?
what to do to point to new memory location everytime?
is this again a design problem?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900