我正在学习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)
答案 0 :(得分:3)
那是一个错误,只需替换
strtok(str,'.');
与
strtok(str,".");
strtok()的第二个参数表示分隔符,并期望使用类型
const char *
,因此必须包含在“”中。
strtok()的语法
char * strtok(char * str,const char * delim);
答案 1 :(得分:3)
strtok()
的语法是:
char *strtok( char *str, const char *delim );
请注意,第二个参数是char指针,而不是char,因此在对strtok()
的每次调用中,第二个参数都应用双引号而不是单引号引起来
更正语法并为可读性添加一些间距后,结果代码为:
#include <stdio.h>
#include <string.h>
int main( void )
{
char str[] = "aa.bb.cc.dd.ee.ff";
char *p;
p = strtok( str, "." );
while( p )
{
printf( "%s\n", p );
p = strtok( NULL, "." );
}
return 0;
}
,并且在运行更正后的源代码时,输出为:
aa
bb
cc
dd
ee
ff
注意:对于现代C编译器,该语句:
return 0;
可以取消,因为main()
的返回值为0(除非另有特别说明)