C语言 使用strtox作为单词生成器,

wtlkbnrh  于 2023-01-01  发布在  其他
关注(0)|答案(1)|浏览(94)

我试图在C语言中创建单词生成器,发现了分段错误消息。
gdb输出:

_GI___strtok_r (
    s=0x562d88201188 "some text without comma", 
    delim=0x562d8820117f " ", save_ptr=0x7f570a47aa68 <olds>) at strtok_r.c:72

带有strtox函数的代码:

char **words = malloc(sizeof(char *) * NUM_WORDS);
    int num_words = 0;
    char *save_ptr;
    char *word = strtok(text, " ");
    while (word != NULL) {

    // Strip leading and trailing whitespace
      while (isspace(*word)) {
        word++;
      }
      int len = strlen(word);
      while (len > 0 && isspace(word[len - 1])) {
        len--;
      }

    // Allocate memory for the word and copy it using strdup()
      words[num_words] = strdup(word);

    // Move to the next word
      num_words++;
      word = strtok(NULL, " ");
    }

如何在文本中使用字数不确定函数?

gab6jxml

gab6jxml1#

不敢相信终于有人要这个了!
您可能希望添加realloc()没有返回NULL的验证。
简而言之,字符串在提供给strtok()的分隔符处被截断,而realloc()用于增长指向这些段中的每一个的指针数组。

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

int main() {
    char buf[] = "Once upon a time there lived a beautiful princess.", *p = buf;
    char **t = NULL; size_t sz = sizeof *t;
    int n = 0;

    while(!!(t=realloc(t,(n+1)*sz))&&!!(t[n]=strtok(p," .\n"))) p=NULL, n++;

    for( int i = 0; i < n; i++ )
        puts( t[i] );

    free( t );

    return 0;
}
Once
upon
a
time
there
lived
a
beautiful
princess
    • 编辑**

然后是可以处理多个输入行的扩展:

int main() {
    char *buf[] = { "Once upon a time\n", "there lived\n", " a beautiful princess.\n" };
    char **t = NULL; size_t sz = sizeof *t;
    int n = 0;

    for( int ln = 0; ln < sizeof buf/sizeof buf[0]; ln++ ) {
        char *p = buf[ln];
        while(!!(t=realloc(t,(n+1)*sz))&&!!(t[n]=strtok(p," .\n"))) p=NULL, n++;
    }

    for( int i = 0; i < n; i++ )
        puts( t[i] );

    free( t );

    return 0;
}
/* Output same as shown above */

strtok()作为strdup()的参数,这样就可以在使用单行输入缓冲区时保留单词。

相关问题