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 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'.