如何获取字符串中第一次出现的字符的索引作为 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
并不重要,但在一般情况下了解它很有用)。
因此,对于您的特定情况,如果您的字符串是 mystring
和 strchr
的返回值是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/