为C

时间:2016-09-28 06:40:00

标签: c pointers

所以这更像是对解释和资源的恳求。我在这里和网上做了一些搜索,但没有找到真正回答这个问题的东西。

我获得了一个将字符串解析为标记的赋值,使用以下原型逐字实现: int makearg(char *s, char ***args);

我是这样使用以下内容:

int makearg(char *s, char ***args){
  char temp[255];
  int count = 0;

  ///////
  //Count words in string
  ///////

  *args = calloc( count , sizeof(char*));
  //OR: *args = (char**) malloc(count * sizeof(char*));

  count = 0; 

  while( //Not at end of s// ){

    //Copy word into temp
    if( //end of word// ){
      *args[count]=calloc( strlen(temp),  sizeof(char));
      //OR: *args[count] = (char*) malloc(count * sizeof(char));

      strcpy(*args[count],temp);

      count++;
    }
  }
return count;
}

int main(){
  char inp[255];
  char **tokens = NULL;
  int count;

  printf("ENTER COMMAND: ");
  fgets(inp,255,stdin);
  count = makearg(inp,&tokens);

  printf("Number of arguments:%d\nArguments:",count);
  int i = 0;
  for(i=0;i<count;i++)
    printf("\n%s", tokens[i]);
  printf("\n");
  return 0;
}

如果我提供类似"testcommand"的内容,程序似乎有效,但如果我输入了两个或更多单词,例如"This is my test command",则会在第二个calloc / malloc行上启动segfaulting 。使用GDB进行调查显示*args[0]按预期返回("This"),但*args[1]试图访问内存中不应该的点。

我使用以下方法开始工作:

int makearg(char *s, char ***args){
  char temp[255];
  int count = 0;
  char** tempargs;

  ///////
  //Count words in string
  ///////

  tempargs = calloc( count , sizeof(char*));

  count = 0; 

  while( //Not at end of s// ){

    //Copy word into temp
    if( //end of word// ){
      tempargs[count]=calloc( strlen(temp),  sizeof(char));

      strcpy(tempargs[count],temp);

      count++;
    }
  }
 *args = tempargs;
 return count;
}

我的问题是,这里的区别是什么?根据我的理解,*args应与使用tokens相同,尤其是malloc的目的。 *args = tempargs末尾的位只是将tokens设置为指向与tempargs相同的内存块。这与首先​​在*args内存中指向malloc有什么不同?

我的教授将上述解决方案描述为他通常采用的方式,但没有提供比#34更好的解释;它剥离了功能体内的一层重定向&#34;。这是有道理的,这是我在尝试寻找答案时在其他地方看到的惯例,但并不能帮助我理解。我亲自询问了一下,但我得到的最好答案是&#34;呃。范围/编译器shenanigans可能。 看起来一样吗?&#34;。

我应该在哪里找到更多信息?

0 个答案:

没有答案