2012-11-01 63 views

回答

5

如果你有兩個指針在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變種。

+0

應該提及一些關於sizeof(type)除以大於1字節的類型的數組的問題? –

+0

@Mike,因爲C自動縮放指針算術,所以實際上並不需要它們是相同的類型。我已經添加了答案。 – paxdiablo

+0

謝謝,這工作! – hesson

3

使用指針運算:

char * pos = strchr(str, c); 
int npos = (pos == NULL) ? -1 : (pos - str);