从strchr获取int而不是指针

hes*_*son 0 c string

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

pax*_*blo 5

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

index = later_pointer - base_address;
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

哪个输出:

Index is 2
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,无论基础类型如何,它都能正确地扩展以提供索引(不是重要的,char但在一般情况下知道它很有用).

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


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

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

请注意,如果您的数组足够大以至于差异不适合,那么这只会成为一个问题int.这是可能的,因为两种类型的范围不是直接相关的,因此,如果您高度重视可移植代码,则应使用ptrdiff_t变体.