-
while loop
why only the first Iteration workin alright ?
Code:
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int val;
struct Node *next;
} ;
typedef struct Node Node ;
void addNode(Node *head,Node *tail)
{
Node *current, *temp;
char Continue='y';
head=(Node*)malloc(sizeof(Node));
head->val=1;
current=head;
do
{
printf("continue?\n");
scanf("%c",&Continue);
temp=(Node*)malloc(sizeof(Node));
printf("value=?\n");
scanf("%d",&(temp->val));
current->next=temp;
current=current->next;
}
while(Continue!='n');
}
void main()
{
Node *head=NULL, *tail=NULL;
addNode(head,tail);
}
TNX
-
#1
Code:
do
{
...
scanf("%c",&Continue);
...
scanf("%d",&(temp->val));
}
while(Continue!='n');
The problem is that %c in the scanf call will read a newline leftover in the input stream from the previous loops read of the integer value. Simplest solution there is to add a space in front of the %c format specifier which will tell the scanf call to ignore leading whitespace.
Code:
scanf(" %c",&Continue);
^ there's a space there now
#2
Code:
head=(Node*)malloc(sizeof(Node));
...
temp=(Node*)malloc(sizeof(Node));
Avoid casting the return value of the malloc call.
#3 You should be setting the next pointer of the newly allocated node to null after you create it, also you head node's next pointer.
#4
main returns int not void.
#5
Code:
void addNode(Node *head,Node *tail)
{
...
}
void main()
{
Node *head=NULL, *tail=NULL;
addNode(head,tail);
}
If you expect to actually do anything with those head/tail pointers in main after the call to addNode then you'll need to change your addNode function to accept pointer-to-pointer-to-Node arguments rather than just simple pointer-to-Node arguments.
-
ok... thank you very much !