【问题标题】:strchr(), How does this correctly find the index of a charstrchr(), 这如何正确找到一个字符的索引
【发布时间】:2013-09-02 18:25:52
【问题描述】:

我正在查看 strchr() 的示例:http://www.cplusplus.com/reference/cstring/strchr/

为什么这会正确找到索引?直觉上它看起来应该给出一个负索引:

#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;
}

【问题讨论】:

    标签: c strchr


    【解决方案1】:

    直觉上看起来它应该给出一个负索引:

    不,因为strchr 返回一个指向该字符所在位置的指针。所以每次strchr 返回非NULL 时,与它开始的指针相比,该指针将位于“更下方”的某个位置。

    【讨论】:

    • 但是如果你用指向堆的指针尝试它仍然是真的吗?
    • 所以是pch指向的地址减去str的地址?
    • @SamDufel 是的,它适用于任何连续的 0 终止内存。
    • @asimes 了解其工作原理的最佳方式是实现您自己的strchr
    • 另一种理解方式是在方格纸上绘制内存内容,用连续地址标记(以任何正数开头)。然后手动模拟strchr() 所做的事情。
    猜你喜欢
    • 2022-10-30
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多