我试图使用sting.h头文件中的两个不同函数(不包括它)strlen()和strtok().Strlen成功执行没有任何错误(但有些警告),strtok在运行时失败.如果我不包含头文件,为什么strlen()函数worknig gine而不是strtok()?我想在链接过程中有一些我不明白的东西.请澄清这种行为.但是,如果我打印一个'%c'而不是'%s'(strtok返回一个垃圾值),程序会成功终止.
码:
int main()
{
char string[] = "This is a String";
printf("\nLength of sting is %d\n",strlen(string));
}
Run Code Online (Sandbox Code Playgroud)
警告: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
Run Code Online (Sandbox Code Playgroud)
码:
int main()
{
char string[] = "This is a String";
printf("\nLength of sting is %d\n",strlen(string));
char *a = strtok(string," ");
printf("%s",a);
}
Run Code Online (Sandbox Code Playgroud)
警告:$ gcc hello.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)
Run Code Online (Sandbox Code Playgroud)
对大多数C标准库隐式地进行链接.您只需要包含您使用的标题(这是警告).
如果不这样做,您的编译器(将代码编译为ANSI C)假定函数返回int,而不是它们记录的返回类型.因此,您的程序具有未定义的行为.始终注意警告!
您必须包含标题string.h和stdio.h.
第一个程序是有效的,因为你很幸运,因为strlen它应该返回一个整数(一个size_t确切地说,但它在你的系统上出现整数的值表示,size_t让程序滑过).
第二个失败,因为strtok返回a char*但int由于你缺少include指令而假定它.int并且char*不是兼容类型,因此您获得的"指针"无效.
| 归档时间: |
|
| 查看次数: |
458 次 |
| 最近记录: |