c/c++语言开发共享将c字符串解析为指针数组时出现分段错误

函数makearg应该计算char数组中的单词数,并将每个单词分解为指针数组中自己的位置。 分段错误似乎是strncpy函数的问题。

int makearg(char s[], char ***args); int main(){ char **args = (char**)(malloc(100)); char *str = "ls is a -l file"; int argc; argc = makearg(str, &args); printf("%d", argc); printf("%c", ''); int i; for(i = 0; i < argc; i++){ puts(args); printf("%c", 'n'); } return 0; } ///////////////////////////////////////// int makearg(char s[], char ***args){ int argc = 0; int charc = 0; int wordstart = 0; while(1){ if(s[charc] == ''){ strncpy(*args[argc], s + wordstart, charc - wordstart); args[argc][(charc - wordstart) + 1] = ''; argc++; break; } if(s[charc] == ' '){ strncpy(*args[argc], s + wordstart, charc - wordstart); args[argc][(charc - wordstart) + 1] = ''; wordstart = charc + 1; argc++; charc++; } else{ charc++; } } return argc; } 

     #include  #include  #include  #include  int makearg(const char s[], char ***args); int main(void){ char **args = NULL; const char *str = "ls is a -l file"; int argc = makearg(str, &args); printf("argc : %dn", argc); int i; for(i = 0; i < argc; i++){ puts(args[i]); free(args[i]); } free(args); return 0; } int wordCount(const char *s){ char prev = ' '; int wc = 0; while(*s){ if(isspace(prev) && !isspace(*s)){ ++wc; } prev = *s++; } return wc; } int makearg(const char s[], char ***args /*out*/){ int argc = wordCount(s); int len; if(argc == 0){ *args = NULL; return 0; } *args = malloc(argc * sizeof(char*)); argc = 0; while(1){ while(isspace(*s)) ++s; if(EOF==sscanf(s, "%*s%n", &len)) break; (*args)[argc] = malloc(len + 1); strncpy((*args)[argc], s, len); (*args)[argc++][len] = ''; s += len; } return argc; } 

    你为args指针数组分配了空间,但是你永远不会为你想要存储的字符串分配空间,所以当你尝试将字符串存储在makearg ,你正在解释任何随机垃圾作为指针,那就是不去上class。

    此外,您只为指针数组分配100 个字节 – 不清楚您希望能分割多少个单词,但malloc调用应该看起来更像

     char **args = malloc(MAX_WORDS * sizeof(char *)); /* no cast required */ 

    然后用循环来执行MAX_WORDS更多malloc调用,以便使用有效指针初始化args

      以上就是c/c++开发分享将c字符串解析为指针数组时出现分段错误相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/519114.html

      (0)
      上一篇 2020年12月5日
      下一篇 2020年12月5日

      精彩推荐