Re: Linked list, no out put,help
- From: "D. Power" <powerd@xxxxxxxxxx>
- Date: Fri, 30 Jun 2006 13:00:13 -0600
In article <1151666370.623666.38780@xxxxxxxxxxxxxxxxxxxxxxxxxxx>,
asm_fool@xxxxxxxxxxx wrote:
dear group,<delurk>
/*Linked list in C*/
Hi;
I can at least point out the most obvious problems with this program.
#include<stdio.h>Here you declare a to be an object of type struct node at file scope so
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}a;
that it is visible to all functions in this file.
Here you allocate enough memory to store an object of type struct node,
void init(int data)
{
struct node *p;
p = malloc(sizeof *p);
p points to that memory (assuming malloc has succeeded, of course).
if(!p)But here, you have assigned the address of a to p; at this point you no
{
printf("mem error");
exit(EXIT_FAILURE);
}
a.data = data;
a.next = NULL;
p = &a;
longer have access to the memory that was allocated above. This is a
memory leak, you lose one such block of memory each time this function
is called.
}You are not creating a linked list here, you are calling the function
int main(void)
{
unsigned int i,j;
for(j=0;j<6;j++)
{
scanf("%d",&i);
init(i);
}
init 5 times, modifying the same file scope variable, a, each time. At
the end of this loop a.data == 5, and a.next is NULL.
while(a.next != NULL)And since a.next == NULL, this loop never executes, that's why you get
no output.
{For a linked list, you need to keep track of the head of the list,
for(j=0;j<6;j++)
printf("value = %d\n",a.data);
}
return 0;
}
personally, I like to use a pointer to the first node (struct node
**headptr), then for each node, then declare the init function as
returning a pointer to node, i.e,
struct node *init (struct node **head,/*other init parameters*/)
{
struct node *current = *head;
struct node *ptr = malloc (sizeof *ptr);
/*Check that malloc succeeded, walk the list until current -> next ==
NULL, initialize the new node*/
return ptr;
}
Another possibility would be to keep a pointer to the last node in the
list, and pass a pointer to that to the init function, updating it to
reflect the new tail if you don't want the overhead of walking the list
each time a new node is created.
HTH
</delurk>
.
This is not the first time I am implementing a linked list.But every
time I
try to do that I get no out put. The above is the same situation. The
above
don't print any out put. Can any one tell me why.
[OT]
I can not configure news reader in my company. Same with the mail
reader. Though I use win98 the pop and nntp server simply functioning.
So I go for the ugly google.
[/OT]
- References:
- Linked list, no out put,help
- From: asm_fool
- Linked list, no out put,help
- Prev by Date: Re: OT: Windows console programs (was Re: Function Pointers)
- Next by Date: Re: Problems with typedef
- Previous by thread: Re: Linked list, no out put,help
- Next by thread: Scope of specifier extern
- Index(es):
Relevant Pages
|