hi, i have this code over here which i cant figure out what's going on.
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *addNode(Node *head, int value);
void printList(Node *head);
void selsort(Node *head);
int main(int argc, char **argv) {
Node *head = NULL;
int i;
int number;
for (i = 0; i < argc; i++) {
if (atoi(argv[i]) != 0) {
number = atoi(argv[i]);
head = addNode(head, number);
}
else {
printf ("Bad data %s, ignoring\n", argv[i]);
}
}
selsort(head);
printf("Sorted numbers:");
printList(head);
return EXIT_SUCCESS;
}
void printList(Node *head) {
Node *cur;
cur=head;
while (cur->next != NULL) {
printf ("%d ", cur->data);
cur = cur-> next;
}
printf ("%d\n", cur->data);
}
Node *addNode(Node *head, int value) {
Node *new;
Node *cur;
new = malloc(sizeof(Node));
if (new == NULL) {
fprintf (stderr, "create: no memory, aborting\n");
exit(1);
}
new->data = value;
new->next = NULL;
if (head == NULL) {
head = new;
}
else {
cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = new;
}
return head;
}
void selsort(Node *head) {
Node *cur;
Node *i;
Node *min;
for (cur = head; cur->next != NULL ; cur = cur->next) {
min = cur;
for (i = cur->next; cur->next != NULL ; i = cur->next) {
if (i->data < cur->data)
min = i;
}
Node *tmp;
tmp = cur;
cur = min;
min = tmp;
}
return;
}
it seems that if i enter more than 1 number in the stdin, the program will not run successfully. After trying to debug it for a long time, I located the problem to the first for loop. However, I dont see anything wrong with it can anyone help me with it? Thanks in advance!