在 strchr
引用中 http://www.cplusplus.com/reference/cstring/strchr/ ,提供了这个例子。
/* strchr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "This is a sample string";
char * pch;
printf ("Looking for the 's' character in \"%s\"...\n",str);
pch=strchr(str,'s');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'s');
}
return 0;
}
为什么从 char
指针 pch
中减去 char
数组 str
加一得到 诠释
? (由 %d
格式类型表示)如果我删除“-str
”,程序将不会执行,直到我更改 %d
到 %s
。
最佳答案
简而言之,这是一个错误:
该表达式可能属于 int
类型,或者您可能在对 printf
的调用中有未定义的行为 .
让我们一步一步来:
您实际上不是从指针中减去数组,而是从指针中减去指针:
在几乎所有情况下,array decays to a pointer to its first element .两个指针的区别是什么类型(仅当它们指向或直接指向同一数组中的元素时才定义)?
ptrdiff_t
(这就是typedef
中的<stddef.h>
的用途。)ptrdiff_t
可能恰好是int
,但不要依赖它。
相反,使用正确的格式说明符:%ti
.
关于c++ - 从 char 指针中减去 char 数组产生一个 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27756958/