【问题标题】:Error when compiling parse_command() function in C在 C 中编译 parse_command() 函数时出错
【发布时间】:2015-02-26 20:24:27
【问题描述】:

我的任务是创建函数:

int parse_command(char *inp, int *argc, char *argv[]);

函数应该:

  • 将字符串inp拆分成单词,并返回单词数。
  • 两个单词由一个或多个空格分隔。
  • 另外argc要设置成字数,
  • argv[0] 应该指向第一个单词,argv[1] 指向第二个单词,依此类推。注意:您应该能够使用argv 指针打印每个单词

这是我的代码:

int parse_command (char *inp, // original string
                   int *argc, // number of words
                   char *argv[]) { // array of words
  // Split the string inp into words (Two words are separated by one or more blank spaces)
  int i = 0;
  int j = 0;
  int a;

  while (inp[i] != '/0' ) {
    while (inp[i] == ' ') {
      if (inp[i + 1] != ' ') {
        inp[i + 1] = '/0'; // end last word (add a /0 to the last word)
        printf("here");
        (*argc)++; // add new word to array of words 
        argv[j++]; // argv(0) = i or j? 
      }
      i++; // it's confusing here
    }
    // The line I commented out below is where I get this error: 
    // array subscript is not an integer
    // argv[argc]= argv+inp[i]; // add letter to current word 
    i++;
  }
  inp[i + 1] = '/0'; // end last word 
  return j; // return the number of words (addition, argc should be set to the number of words) 
}

当我尝试向当前单词添加字母时出现错误。错误是:

array subscript is not an integer

【问题讨论】:

  • 您的代码中没有 36 行 ..
  • 我认为当代码出现在项目符号点之后时存在一些格式问题。
  • while (inp[i] != '/0' ) { --> while (inp[i] != '\0' ) { 或者只是:while (inp[i]) {

标签: c arrays pointers


【解决方案1】:

如果您已将 argc 声明为 int*,则第“36”行应如下所示:

argv[(*argc)] = argv+inp[i];

这样你就可以取消引用指向整数的指针并得出一个整数。

【讨论】:

  • OP 实际上注释掉了这一行,但它是argv[argc]= argv+inp[i]
  • 我假设它已被注释掉,因为它会导致错误(来自评论)。 argv[argc] 将成为问题,因为 [] 期望它们之间有一个整数。相反,由于 argc 被声明为 int *,所以 OP 正在传递一个指针。通过执行 (*argc) 取消引用它为他们提供了数组下标所需的 int。
  • 哦,不,你是对的(因此赞成),我只是向你指出 OP 代码中的实际行是什么,以便你可以将其编辑到你的答案中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多