0

我有一个程序将命令行提示读取到链表中添加

one two three 

进入列表。我正在编译使用

gcc -o code code.c 

但是对于我运行时的第二个提示

./code one two three 

它还将 ./code 添加到列表的开头

./codeonetwothree

当我只想

onetwothree

任何关于如何在不添加 ./code 到我的链接列表中进行编译的建议将不胜感激!

如果需要,以下是我的代码:

#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;
  }
}
4

2 回答 2

1

arg[0] 是正在执行的文件的名称。所以你应该用 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);
            }
    }
于 2014-04-17T20:29:59.873 回答
1

argv[0]是程序的名称。

如果您不想要程序的名称,请从以下位置开始处理argv[1]

for(the_count = 1; the_count < argc; the_count++){
于 2014-04-17T20:30:21.227 回答