A String constant is actually a character array. For example, welcome to www.bkjia.com is a character array ending with '\ 0.
A common usage of string constants is as function parameters, such as the common printf ("welcome to www.bkjia.com"). String parameters actually access the string through character pointers. The printf () function accepts a pointer pointing to the first character in the character array. A String constant can be accessed through a pointer to its first element.
The stringcopy (char * source, char * target) function in the following program implements the function of copying the string pointed to by the target pointer to the position pointed by the source pointer.
# Include <stdio. h> void stringcopy (char * source, char * target); int main () {char str_a [] = "Welcome to www.bkjia.com"; char str_ B [] = ""; int wait; printf ("str_a is % s \ n", str_a); printf ("str_ B is % s \ n", str_ B); stringcopy (str_ B, str_a ); printf ("\ n" after the function is called); printf ("str_a is % s \ n", str_a); printf ("str_ B is % s \ n", str_ B ); scanf ("% d", & wait) ;}void stringcopy (char * source, char * target) {int I; I = 0; while (source [I] = Target [I])! = '\ 0') I ++ ;}
Program running result:
Str_a is Welcome to www. bkjia. comstr_ B. after calling the function, str_a is o www. bkjia. comstr_ B is Welcome to www.bkjia.com
Because parameters are passed through values, the source and target are executed every time in the loop, and they will forward a character along the corresponding array, until the end character '\ 0' in the targrt is copied to the source.
Experienced programmers like to write as follows:
void stringcopy(char *source, char *target){while((*source++ = *target++) != '\0');}
In this function, the auto-increment operations of source and target are placed in the testing part of the loop.
You can further refine the program. The expression is redundant compared with '\ 0'. You only need to judge whether the expression value is 0.
void stringcopy(char *source, char *target){while(*source++ = *target++);}
This method does not seem easy to understand, but it is advantageous for C Programs to use this method.