Question

I have to make a linked list from arguments entered from the command line. You are supposed to enter integers and make a linked list out of them. When you enter -1, then stop reading from the command line. Fairly simple, but I am having some trouble. What I have is:

#include <stdlib.h>

struct node
{
  int grade;
  struct node *next;
};

int
main (int argc, char *argv[])
{
  struct node *root;
  root = (struct node *) malloc (sizeof (struct node));
  root->next = 0;
  root->grade = 0;
  int i;
  for (i = 0; i < argc; i++)
    {
      if (&argv[i] == -1)
        {
          break;
        }
      else
        {
          struct node *new_item_ptr;
          new_item_ptr = malloc (sizeof (struct node));
          new_item_ptr->grade = (*int) argv[i];
          (*new_item_ptr).next = root;
          root = new_item_ptr;
        }
    }
}

I think I'm pretty close, but there are a few things that doesn't work correctly. For example, I don't think for(i = 0; i < argc; i++) is correct. And the compiler says that new_item_ptr->grade = (*int) argv[i]; is wrong also. Can anyone help me out with this? I think I'm close just have a few minor errors.

No correct solution

OTHER TIPS

To begin with, you have malloc'ed a structure which is totally unnecessary. If the user enters no data, you can return an empty list indicated by root = NULL. So, the initial part could be:

root = ( struct node * ) NULL;
if ( argc < 2 )
    return ( 0 );

As your code stands, the first node will always have 0 for root->grade. In the loop, you should allocate the memory and convert the argv[i] to integer using atoi. Finally, your loop should start with i=1 because argv[0] is the command name itself.

The various argv[i]s are C-strings (char*) not integers. You need to convert them to integers, and the best way to do that is with the atoi function:

int value = atoi(argv[i]);
if (value == -1) {
    break;
} else {
    // etc.
}

The function name atoi is supposed to be a mnemonic for "ASCII to integer." The syntax you're using to assign the next field of new_item_ptr is a little more complicated than it needs to be as well. You can use the arrow syntax to assign the next field just as you did to assign the grade field. This part should look like:

new_item_ptr->grade = atoi(argv[i]);
new_item_ptr->next = root;

Or, better still, re-use the value variable created at the top of this iteration of the for loop instead of running atoi again:

new_item_ptr->grade = value;
new_item_ptr->next = root;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top