Question

I have a program reading command line prompts into a linked list adding

one two three 

into the list. I am compiling using

gcc -o code code.c 

but for the second prompt when I run

./code one two three 

it also adds ./code to the beginning of the list making it

./codeonetwothree

when I only want

onetwothree

Any suggestions on how to compile without adding ./code into my linked list would be greatly appreciated!

Below is my code if needed:

#include <stdio.h>
#include <stdlib.h>

typedef struct list_node_s{
    char the_char;
    struct list_node_s *next_node;
}list_node;

void insert_node(list_node *the_head, char the_char);
void print_list(list_node *the_head);

int main(int argc, char *argv[]){

    list_node the_head = {'\0', NULL};
    int the_count, the_count2;
    for(the_count = 0; the_count < argc; the_count++){
            for(the_count2 = 0; argv[the_count][the_count2] != '\0'; the_count2++){
                    char next_char = argv[the_count][the_count2];
                    insert_node(&the_head, next_char);
            }
    }

    print_list(&the_head);
    int nth_node = 3;
    printf("Node at the %d spot: ", nth_node);
    printf("%c \n", the_nth_node(&the_head, nth_node));
    return (0);
}

void insert_node(list_node *the_head, char the_char){

   list_node * current_node = the_head;
   while (current_node->next_node != NULL) {
    current_node = current_node->next_node;
   }
  current_node->next_node = malloc(sizeof(list_node));
  current_node->next_node->the_char = the_char;
  current_node->next_node->next_node = NULL;
}

void print_list(list_node *the_head){
    if(the_head == NULL){
            printf("\n");
    }else{
            printf("%c", the_head->the_char);
            print_list(the_head->next_node);
    }

}
int the_nth_node(list_node* head, int index_of)
{
  list_node* current_node = head;
  int count_1 = 0; /* the index of the node we're currently
              looking at */
  while (current_node != NULL)
  {
   if (count_1 == index_of)
      return(current_node->the_char);
   count_1++;
   current_node = current_node->next_node;
  }
}
Was it helpful?

Solution

argv[0] is the name of the program.

If you don't want the name of the program, start processing at argv[1]

for(the_count = 1; the_count < argc; the_count++){

OTHER TIPS

arg[0] is the name of the file being executed. so you should initialize your outer loop counter with 1

for(the_count = 1; the_count < argc; the_count++){
            for(the_count2 = 0; argv[the_count][the_count2] != '\0'; the_count2++){
                    char next_char = argv[the_count][the_count2];
                    insert_node(&the_head, next_char);
            }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top