954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Connecting link lists

Hello, I want to make a linked list program consisting of one main link, and each main links have sub link.

Main 1 -> Main 2 -> Main 3 -> ... -> Main N -> NULL
   |                |              |                        |
Sub 1-1     Sub 2-1     ...                      ...
   |                |
Sub 1-2     Sub 2-2
   |               |
  ...             ...


I have two structs for these:

struct NodeSmall
{
	int documentNum;
	NodeSmall *nextNum;
	NodeSmall()
	{
		documentNum = 0;
		nextNum = NULL;
	}
};

struct NodeBig
{
	string keyword;
	NodeBig *nxtkyw; //Link to next keyword
	NodeSmall *docNum; //Link to document number

	NodeBig()
	{
		keyword = "";
		nxtkyw = NULL;
	}
	
};


And I have a test main which reads first line from text file:

int main()
{

	string line, key;
	int number;
	ifstream dbfile;
	dbfile.open("docdb.txt");

	dbfile >> key >> number;

	NodeBig *head = new NodeBig;
	NodeSmall *docNum = new NodeSmall;
	
	head->keyword = key;
	head->nxtkyw = NULL;
	head->docNum->documentNum = number;

	cout << "keyword is " << head->keyword << " and it is on " << head->docNum->documentNum;
}


It does not give compiler error (vs2008) but it gives stopped working error after running the program. I think I've made a mistake while connecting link lists together. But I cannot find similar probles on internet. What should I do for fixing this error? Thank you.

PcCopat
Newbie Poster
4 posts since May 2005
Reputation Points: 10
Solved Threads: 0
 

Instead of

NodeSmall *docNum = new NodeSmall;

you have to use

head->docNum = new NodeSmall;
kbshibukumar
Junior Poster in Training
65 posts since Jan 2009
Reputation Points: 12
Solved Threads: 8
 

Thank you! It worked. Can you explain the reason?

PcCopat
Newbie Poster
4 posts since May 2005
Reputation Points: 10
Solved Threads: 0
 

When you say NodeSmall *docNum = new NodeSmall; a new NodeSmall is created in memory and head->docNum will not point to the same. Hence, head->docNum will be NULL and as you tried to access an element of NULL, the program crashed.

kbshibukumar
Junior Poster in Training
65 posts since Jan 2009
Reputation Points: 12
Solved Threads: 8
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: