【发布时间】:2017-08-23 20:35:48
【问题描述】:
我尝试使用 sting.h 头文件(不包括它)strlen() 和 strtok() 中的两个不同函数。 strlen 成功执行,没有任何错误(但有一些警告),strtok 在运行时失败。如果我不包含头文件,为什么 strlen() 函数可以工作而不是 strtok() ?我想链接过程中有些东西我不明白。请澄清这种行为。但是,如果我将 a 打印为 '%c' 而不是 '%s' (strtok 返回垃圾值),程序将成功终止。
代码:
int main()
{
char string[] = "This is a String";
printf("\nLength of sting is %d\n",strlen(string));
}
警告: hello.c:在函数“main”中: hello.c:4:2:警告:内置函数“printf”的隐式声明不兼容 [默认启用] hello.c:4:37:警告:内置函数‘strlen’的隐式声明不兼容 [默认启用] hello.c:4:2:警告:格式“%d”需要“int”类型的参数,但参数 2 的类型为“long unsigned int”[-Wformat]
输出: $ ./a.out
Length of sting is 16
代码:
int main()
{
char string[] = "This is a String";
printf("\nLength of sting is %d\n",strlen(string));
char *a = strtok(string," ");
printf("%s",a);
}
警告: $ gcc 你好.c hello.c:在函数“main”中: hello.c:4:2:警告:内置函数“printf”的隐式声明不兼容 [默认启用] hello.c:4:37:警告:内置函数‘strlen’的隐式声明不兼容 [默认启用] hello.c:4:2:警告:格式“%d”需要“int”类型的参数,但参数 2 的类型为“long unsigned int”[-Wformat] hello.c:5:12: 警告:初始化使指针从整数而不进行强制转换[默认启用]
输出: $ ./a.out
Length of sting is 16
Segmentation fault (core dumped)
【问题讨论】:
-
如果您可以执行您的程序,则链接过程成功。
-
如果这是真的,那么 strtok() 函数的实现中有些东西我不明白。如果 string.h 不包括在内,它会返回一个垃圾字符,而 strlen() 可以正常工作。但是,如果我包含头文件 strtok() 也可以按预期工作。