I'm working with a program written in C that involves comparing hypehenated surnames. For example, it might compare Mary Jay-Blige to Mary Kay-Blige. The code that 开发者_JAVA技巧finds the hyphen and sets a variable to it's position is:
APT_String LAST_NAME
char * p_ich;
int iPosHyphen;
p_ich = strchr(LAST_NAME,'-');
iPosHyphen = p_ich-LAST_NAME+1;
where APT_String is a data type for IBM's DataStage.
I inherited the above code, and it appears to "work", but I would like some clarification on the p_ich-LAST_NAME+1
operation.
Namely, if strchr()
returns the location of the first '-', how is C handling this arithmetic?
If I call cout<<p_ich;
, I get -Blige
. So I guess it returns the remainder of the string once the specified char is found?
Yes, strchr returns the address of the first occurence (not the index). So you subtract the original string (address) from that to get the position of the hyphen. But here the +1 gets you the first position (index) after the hyphen.
Such that p_ich[iPosHyphen] == 'B'.
This is very basic C pointer arithmetic and you can easily find a lot of information about it.
Subtracting one pointer from another yields distance between their indices as if they were part of the same array. In your example it will be distance between *p_ich* and *LAST_NAME*. With standard char type distance will be equal to difference between memory addresses but in general:
ptr1-ptr2 == ((unsigned long)ptr - (unsigned long)ptr2)/sizeof(*ptr)
精彩评论