简体   繁体   English

符合fgets()的分段错误-C

[英]Segmentation fault on line with fgets() - C

I have this code in my program: 我的程序中有以下代码:

char* tok = NULL;
char move[100];

if (fgets(move, 100, stdin) != NULL) 
{
    /* then split into tokens using strtok */
    tok = strtok(move, " "); 

    while (tok != NULL)
    {
        printf("Element: %s\n", tok);
        tok = strtok(NULL, " ");
    }
}

I have tried adding printf statements before and after fgets, and the one before gets printed, but the one after does not. 我试过在fgets之前和之后添加printf语句,并在打印之前添加一个,但在之后不打印。 I cannot see why this fgets call is causing a segmentation failure. 我看不到为什么此fgets调用导致分段失败。

If someone has any idea, I would much appreciate it. 如果有人有任何想法,我将不胜感激。

Thanks Corey 谢谢科里

The strtok runtime function works like this strtok运行时函数的工作原理如下

the first time you call strtok you provide a string that you want to tokenize 第一次调用strtok时,会提供要标记化的字符串

char s[] = "this is a string";

in the above string space seems to be a good delimiter between words so lets use that: 在上述字符串空间中,单词之间似乎是一个很好的分隔符,因此让我们使用它:

char* p = strtok(s, " ");

what happens now is that 's' is searched until the space character is found, the first token is returned ('this') and p points to that token (string) 现在发生的是搜索“ s”直到找到空格字符,返回第一个标记(“ this”),p指向该标记(字符串)

in order to get next token and to continue with the same string NULL is passed as first argument since strtok maintains a static pointer to your previous passed string: 为了获得下一个标记并继续使用相同的字符串,因为strtok维护指向先前传递的字符串的静态指针,所以将NULL作为第一个参数传递:

p = strtok(NULL," ");

p now points to 'is' p现在指向“是”

and so on until no more spaces can be found, then the last string is returned as the last token 'string'. 依此类推,直到找不到更多空间,然后最后一个字符串作为最后一个标记“ string”返回。

more conveniently you could write it like this instead to print out all tokens: 更方便的是,您可以这样写,而不是打印所有令牌:

for (char *p = strtok(s," "); p != NULL; p = strtok(NULL, " "))
{
  puts(p);
}

EDITED HERE: 在这里编辑:

If you want to store the returned values from strtok you need to copy the token to another buffer eg strdup(p); 如果要存储从strtok返回的值,则需要将令牌复制到另一个缓冲区,例如strdup(p);。 since the original string (pointed to by the static pointer inside strtok) is modified between iterations in order to return the token. 因为原始字符串(由strtok内的静态指针指向)在两次迭代之间进行了修改,以返回令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM