#include <stdio.h>
#include <string.h>
int main ()
{
const char str[] = "http://www.tutorialspoint.com";
const char ch = '.';
char *ret;
ret = strchr(str, ch);
printf("String after |%c| is - |%s|\n", ch, ret);
return(0);
}
此代码是从tutorialspoint复制的。
据我了解,ret
是一个指向字符的指针。要使用指针所指向的值/内容,我执行*ret
。
但是,在本示例中,只需调用 ret
,printf()
就会打印出 .tutorialspoint.com
。为什么我们不使用 *ret
来获取 .tutorialspoint.com
因为该字符串是 ret
中的值,可以通过 访问>*ret
?
最佳答案
查看 %s
转换说明符属性。当在 printf()
中使用时,它需要一个 char *
类型的参数,因此它得到了。一切都很好。
引用 C11
标准,第 §7.21.6.1 章
s
If nol
length modifier is present, the argument shall be a pointer to the initial element of an array of character type.280) Characters from the array are written up to (but not including) the terminating null character. [...]
换句话说,要使用 %s
打印出字符串,您必须提供指向字符串开头的指针,即 res
,而不是 *res
。
关于C 编程 strchr 返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36755360/