为何strpbrk()返回的指针需解引用,而strrchr()返回的无需?
关于strpbrk()与strrchr()使用差异的疑问解答
测试代码
#include <stdio.h> #include <string.h> int main(void){ const char *string1 = "This is a test"; const char *string2 = "beware"; printf( "%s\"%s\"\n'%c'%s\n\"%s\"\n", "Of the characters in ", string2, *strpbrk( string1, string2 ), " appears earliest in ", string1 ); puts(""); const char *stringg1 = "A zoo has many animals including zebras"; int c = 'z'; printf( "%s\n%s'%c'%s\"%s\"\n", "The remainder of string1 beginning with the", "last occurrence of character ", c, " is: ", strrchr(stringg1, c)); }
运行输出
Of the characters in "beware" 'a' appears earliest in "This is a test" The remainder of string1 beginning with the last occurrence of character 'z' is: "zebras"
疑问解答
核心原因就是你用的printf格式符不一样,两个函数返回的都是指针,但格式符对传入参数的要求完全不同:
用
strpbrk()时,你对应的格式符是%c——这个格式符需要传入单个字符。strpbrk()返回的是指向第一个匹配字符的内存地址(指针),必须用*解引用这个指针,才能拿到地址里存的那个字符,传给%c才能正确打印出字符。要是不解引用,直接把指针(一串数字地址)传给%c,printf会把这个地址值当成字符的ASCII码,打印出乱码。用
strrchr()时,你对应的格式符是%s——这个格式符需要传入字符串的首地址,printf会从这个地址开始,一直打印到遇到字符串结束符\0为止。strrchr()返回的刚好是最后一个'z'的内存地址,而从这个地址往后的内容就是"zebras",直接把这个指针传给%s,printf就能正确打印从该位置开始的字符串。
至于解引用strrchr()会崩溃:解引用后你得到的是单个字符'z'(它的ASCII值是122),把这个值传给%s的话,printf会把122当成一个内存地址去访问——但这个地址是程序没有权限访问的内存区域,直接触发内存访问错误,程序就崩溃了。
内容的提问来源于stack exchange,提问作者Magical Bologna
相关产品推荐
相关产品推荐

