Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Linked list - debug -911

Status
Not open for further replies.

giahan

Programmer
Sep 1, 2000
139
0
0
US
All,
I have tried to debug my code but could not find any error but I get error. This supposed to print out node 34 and node 48. For some reasons, I got 1 weird number and 34 and 48 plus error. Thanks a lot in advance.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>

struct NODE
{
int nodevalue;
NODE *next;
};

NODE *addnode(int value, NODE *position) /*our algorithm starts here*/
{
NODE *newNodeAdded;
newNodeAdded = new NODE;
if(newNodeAdded==NULL)
printf(&quot;Memory shortage&quot;);
else
{
newNodeAdded->nodevalue = value;
newNodeAdded->next = position->next;
position->next=newNodeAdded;
}
return newNodeAdded;
}
void printnode(NODE *ptr )
{
printf(&quot;nodeValue ->%d\n&quot;, ptr->nodevalue );
}
void printlist(NODE *ptr )
{
while( ptr != NULL ) /* continue whilst there are nodes left */
{
printnode( ptr ); /* print out the current node */
ptr = ptr->next; /* goto the next node in the list */
}
}
main()
{
NODE *list;


list = new NODE;/*list initialized*/

addnode(48,list);
addnode(34,list);
printlist(list);
delete list;

return 0;
}
GH
 
giahan,
The error and the wierd value come from the two uninitialised members of the
Code:
list
struct.

If you initialise
Code:
list->next
to
Code:
NULL
then that's your terminator for the list. I got an Access Violation which says it's pointer troubles.

The first value you get printed out is
Code:
list->nodevalue
- if you convert your wierd number to hex it's probably &xcdcdcdcd or similar. This type of number means it's uninitialised - this works for pointers too (debug mode only).
You probably don't want to print this first value - maybe change either the call to printlist() or printlist() itself.

Hope this helps.
Rob
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top