gpt4 book ai didi

C 编程 strchr 返回指针

转载 作者:行者123 更新时间:2023-11-30 20:04:47 25 4
gpt4 key购买 nike

#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

但是,在本示例中,只需调用 retprintf() 就会打印出 .tutorialspoint.com。为什么我们不使用 *ret 来获取 .tutorialspoint.com 因为该字符串是 ret 中的值,可以通过 访问>*ret

最佳答案

查看 %s 转换说明符属性。当在 printf() 中使用时,它需要一个 char * 类型的参数,因此它得到了。一切都很好。

引用 C11 标准,第 §7.21.6.1 章

s
If no l 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com