(C) string comparison function, pointer array and array pointer
Problem description:
Write a function to compare two strings (string_compare ).
Program Analysis:
(1) Main Idea: After two strings are passed in, compare each element of the two strings. If the first comparison is not equal, do not make it into the following comparison. In this way, return a subtraction value (that is, the two elements that are not equal at the beginning of the two arrays subtract, And the return value (int type) is the ASCII code value subtract ). In the comparison process, 0 is returned if the values are equal. In other cases, the subtract value is returned.
(2) Main method: define and initialize the pointer array. Then implement the Code according to the above idea.
The Code is as follows:
/*** Pointer array (1) int * a [10] is a pointer array ---> is an array (the elements in each array are of the int * type) (2) int (* a) [10] is an array pointer ---> pointing to an array (ten int-type arrays) Note: *, [], () Priority increases sequentially. The following example uses a pointer array .. **/# Include
# Includeint string_compare (const char * str1, const char * str2) {assert (str1); // ASSERT (f) assert (str2);/* In Debug mode, after each running, the expression in parentheses is calculated. If the expression is 0, the execution is interrupted. A warning box is displayed. You can select "continue" and "retry ", in Release mode, this statement is not compiled into the code. ASSERT is generally used in the program to confirm the correctness of parameters. That is, when calling an internal function, the caller must ensure that the parameters are correct, you can use ASSERT to check whether the parameters meet the requirements. */While (* str1 = * str2) // checks whether the elements in the two arrays are equal {str1 ++; // points the two pointers to the next position; continue to compare str2 ++; if (* str1 = '\ 0') // both sides compare to' \ 0', all equal {return 0; // return 0, returns * str1-* str2; // if not, returns a positive or negative value} int main () {char * ch [2]; ch [0] = "AB"; // initialize the element of the pointer array to point it to the first address of the first element of the string ch [1] = ""; // same as printf ("% d \ n", string_compare (ch [0], ch [1]); // call this function return 0 ;}