c - 从 strchr 获取 int 而不是指针

标签 c string

如何获取字符串中第一次出现的字符的索引作为 int 而不是指向其位置的指针?

最佳答案

如果在 C 中有两个指向数组的指针,您可以简单地执行以下操作:

index = later_pointer - base_address;

哪里base_address是数组本身。

例如:

#include <stdio.h>
int main (void) {
    int xyzzy[] = {3,1,4,1,5,9};       // Dummy array for testing.

    int *addrOf4 = &(xyzzy[2]);        // Emulate strchr-type operation.

    int index = addrOf4 - xyzzy;       // Figure out and print index.
    printf ("Index is %d\n", index);   //   Or use ptrdiff_t (see footnote a).

    return 0;
}

哪些输出:

Index is 2

如您所见,无论基础类型如何,它都能正确缩放以提供索引(这对 char 并不重要,但在一般情况下了解它很有用)。

因此,对于您的特定情况,如果您的字符串是 mystringstrchr 的返回值是chpos , 只需使用 chpos - mystring获取索引(假设您当然找到了字符,即 chpos != NULL)。


(a) 正如评论中正确指出的那样,指针减法的类型是 ptrdiff_t其中,可能与 int 有不同的范围.为了完全正确,索引的计算和打印最好按以下方式完成:

    ptrdiff_t index = addrOf4 - xyzzy;       // Figure out and print index.
    printf ("Index is %td\n", index);

请注意,只有当您的数组足够大以至于差异不适合 int 时,这才会成为问题。 .这是可能的,因为这两种类型的范围没有直接关系,所以如果您高度重视可移植代码,您应该使用 ptrdiff_t变体。

关于c - 从 strchr 获取 int 而不是指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13187254/

相关文章:

javascript - 从 Javascript 数组中删除相似的字符串

Javascript 字符串比较未显示正确结果

c - 为 RANSAC 采样生成两个随机数

c - 如何打印字符串数组的某些部分?

c - memcpy() 用于 3D 数组的可变维度

c - 为什么以下 temp 和 stNode 显示不同的值?

string - 如何将 MIPS 数字字符串转换为十六进制

python - 在Python中返回按元音计数过滤的列表的函数

java - 正则表达式模式表达式

c - 将变量传递给函数并更改其全局值