我正在学习C字符串操作,并使用strtok()函数我的代码以警告结束,然后输出是分段错误。
以下是源代码(在文件token3.c中):

#include <stdio.h>
#include <string.h>
int main() {
    char str[] = "aa.bb.cc.dd.ee.ff";
    char *p;
    p = strtok(str, '.');
    while (p != NULL) {
        printf("%s\n", p);
        p = strtok(NULL, '.');
    }
    return 0;
}

编译期间的警告:
token3.c: In function ‘main’:
token3.c:6:15: warning: passing argument 2 of ‘strtok’ makes pointer from integer without a cast [-Wint-conversion]
      p=strtok(str,'.');
                   ^~~
In file included from token3.c:2:0:
/usr/include/string.h:335:14: note: expected ‘const char * restrict’ but argument is of type ‘int’
extern char *strtok (char *__restrict __s, const char *__restrict __delim)
               ^~~~~~
token3.c:9:17: warning: passing argument 2 of ‘strtok’ makes pointer from integer without a cast [-Wint-conversion]
    p=strtok(NULL,'.');<br>
                  ^~~
In file included from token3.c:2:0:
/usr/include/string.h:335:14: note: expected ‘const char * restrict’
but argument is of type ‘int’
    extern char *strtok (char *__restrict __s, const char *__restrict __delim)
                                               ^~~~~~<

预期产量:
aa
bb
cc
dd
ee
ff

实际产量:
Segmentation fault(core dumped)

最佳答案

那是个错误,换个

strtok(str,'.');

具有
strtok(str,".");

strtok()的第二个参数表示分隔符,需要类型
常量字符*
所以必须用“”括起来。
strtok()的语法
char*strtok(char*str,const char*delim);

关于c - c中strtok()的用法显示警告并返回段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56087571/

10-13 08:25