我正在学习C字符串操作,并且正在使用strtok()
函数。我的代码最终导致警告,然后输出是分段故障。
这是源代码(在文件中 汇编过程中的警告: 预期输出: 实际输出:#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("%sn", 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((的第二个参数是指定器,并期望类型
const char *
,因此必须包含在"。
中strtok((
的语法char *strtok(char *str,const char *delim(;
strtok()
的语法是:
char *strtok( char *str, const char *delim );
请注意,第二个参数是炭指针,而不是字符,因此每个呼叫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( "%sn", p );
p = strtok( NULL, "." );
}
return 0;
}
运行更正的源代码时,输出为:
aa
bb
cc
dd
ee
ff
注意:使用现代C编译器,该语句:
return 0;
可以作为从main()
的返回(另外未具体说明(的返回而被消除。