简体   繁体   English

从char指针减去char数组会产生一个int吗?

[英]Subtracting char array from char pointer produces an int?

In the strchr reference at http://www.cplusplus.com/reference/cstring/strchr/ , this example is provided. http://www.cplusplus.com/reference/cstring/strchr/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;
}

Why does subtracting the char array str from the char pointer pch plus one give an int ? 为什么从char指针pch加1减去char数组str给出一个int (as denoted by the %d format type) If I remove " -str ", the program wouldn't execute until I change %d to %s . (以%d格式类型表示)如果删除“ -str ”,则在将%d更改为%s之前该程序将不会执行。

The short of it is, that's a bug : 简而言之,这是一个错误
That expression might be of type int , or you might have Undefined Behavior in the call to printf . 该表达式可能是int类型,或者在调用printf可能具有“ 未定义行为 ”。

Let's take it step by step: 让我们逐步进行:

  1. You are not actually subtracting an array from a pointer, but a pointer from a pointer: 您实际上不是从指针减去数组,而是从指针减去指针:
    In nearly all contexts, an array decays to a pointer to its first element . 在几乎所有情况下, 数组都会衰减到指向其第一个元素的指针

  2. What type is the difference of two pointers (which is only defined if they point at or directly behind elements from the same array)? 两个指针的区别是什么类型(仅当它们指向或指向同一数组中的元素时才定义)?

    ptrdiff_t (That's what that typedef in <stddef.h> is for.) ptrdiff_t (这就是<stddef.h>中的typedef目的。)

  3. ptrdiff_t might happen to be int , but don't depend on it. ptrdiff_t可能恰好是int ,但不要依赖于它。
    Instead, use the proper format-specifier: %ti . 而是使用正确的格式说明符: %ti

Array names decays to pointers (in most cases) to its first element. 数组名称会衰减(在大多数情况下)指向其第一个元素的指针。 Subtraction of two pointers yields an data of ptrdiff_t type, provided both points to elements of the same array. 如果两个指针都指向同一数组的元素,则将两个指针相减会生成ptrdiff_t类型的数据。

You are looking at one of the oddities of C/C++ and pointers. 您正在看C / C ++和指针的怪异之一。 Pointer and array syntax and semantics are simply nuts. 指针和数组的语法和语义简直就是坚果。

str is a pointer to a char (as well as an array). str是一个指向char(以及数组)的指针。 pch is a pointer to a char as well. pch也是指向char的指针。

If you subtract two pointers to the same type you get the number of elements between them. 如果您减去两个指向相同类型的指针,则会得到它们之间的元素数量。

You can even do 你甚至可以做

    3 [str] ;

which is equivalent to 相当于

   str[3] ;

and is equivalent to 相当于

   *(str+3) ;

Your expression: 您的表情:

  pch - 1

has the type pointer to char. 具有指向char的类型指针。 Your expression 你的表情

  pch - str

has the type int. 具有类型int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM