String pointer and pointer variable pointing to the string

Source: Internet
Author: User
From: http://s319.dlut.edu.cn/educ/83.htm

§ 8. 4 pointer to a string and pointer to a string

8.4.1 String Representation

In CProgram.

1. Use a character array.

[Example: 8.11]

Void main (void)

{Static char string [] = "I love China! ";

Printf ("% s \ n", string );

}

Runtime output: I love China!

Like the preceding array attribute, string is the array name, which represents the first address of the character array (see Figure 8.17 ). String [4] indicates the element (V) with the serial number 4 in the array. In fact, string [4] is * (string + 4), and string + 4 is the pointer to the character "V.

2. Use a character pointer.

You can define a character pointer instead of a character array. Point A character pointer to a character in a string.

[Example: 8.12]

Void main (void)

{Char * string = "I love China! ";

Printf ("% s \ n", string );

}

No character array is defined here, but the C language processes string constants by character array. In fact, a character array is opened in the memory to store the string array. The program defines a character pointer variable string. And assign the first address of the string (that is, the first address of the character array that stores the string) to it (see Figure 8.18 ). Some people think that string is a string variable! "It is inaccurate to assign this string variable. Define the string part:

Char * string = "I love China! ";

It is equivalent to the following two rows:

Char * string;

String = "I love China! ";

We can see that string is defined as a pointer variable that points to character-type data. Note that it can only point to one character variable or other character-type data, and cannot point to multiple character data at the same time, not to mention "I love China! "These characters are stored in string. Just put "I love China! "First address to the pointer variable string (not to assign the string to * string ). Therefore, do not consider the above definition line as equivalent:

Char * string;

* String = "I love China! ";

In the output, use

Printf ("% s \ n", string );

% S indicates that a string is output, and the character pointer variable name is string. the system first outputs a character data to which it points, and then automatically adds 1 to the string to point to the next character, then output a character ,......, Until the string end flag '\ 0' is encountered. Note: In the memory, the string is automatically appended with a '\ 0' (8.18), so the end position of the string can be determined during output.

You can output a string using the character array name or character pointer variable. For a numeric array, you cannot use the array name to output all its elements. For example:

Int I [10]

:

Printf ("% d \ n", I );

No. Only one element can be output one by one. Obviously, strings can be viewed as a whole for processing, and a string can be input and output as a whole.

You can use the subscript method or pointer method to access characters in a string.

[Example 8.13] Copy string a to string B.

Void main (void)

{Char a [] = "I am a boy.", B [20];

Int I;

For (I = 0; * (a + I )! = '\ 0'; I ++)

* (B + I) = * (a + I );

* (B + I) = '\ 0 ';

Printf ("string a is: % s \ n", );

Printf ("string B is :");

For (I = 0; B [I]! = '\ 0'; I ++)

Printf ("% C", B [I]);

Printf ("\ n ");

}

The program running result is:

String A is: I am a boy.

String B is: I am a boy.

Both A and B in the program are defined as character arrays. The address method can be used to represent array elements. In the for statement, first check whether a [I] is '\ 0' (today a [I] is expressed in the form of * (a + I ). If the value is not equal to '\ 0', it indicates that the string has not been processed completely. Then, the value of a [I] is assigned to B [I], that is, copying a character. In the for loop, all string a is copied to string B. Finally, we should copy '\ 0', so there are: * (B + I) =' \ 0 ';

At this time, the value of I is the number of valid characters N plus 1. In the second for loop, a subscript is used to represent an array element (that is, a character ). You can also set a pointer variable to point to different characters in the string by changing its value.

[Example 8.14] Use Pointer variables to handle example 8.13.

Void main (void)

{Char a [] = "I am a boy.", B [20], * P1, * P2;

Int I;

P1 = A; P2 = B;

For (; * P1! = '\ 0'; P1 ++, P2 ++)

* P2 = * P1;

* P2 = '\ 0 ';

Printf ("string a is: % s \ n", );

Printf ("string B is :");

For (I = 0; B [I]! = '\ 0'; I ++)

Printf ("% C", B [I]);

Printf ("\ n ");

}

P1, P2 is a pointer variable that points to the character type data. The values of P1 and P2 are the first addresses of string a and string B respectively. * When the initial value of P1 is 'I, the value assignment statement "* P2 = * P1;" is used to set the character' I '(the first character in string) assign the element to P2 until * P1 is set to '\ 0. Note that the values of P1 and P2 are constantly changing. The program must ensure that P1 and P2 are synchronized.

8.4.2 string pointer as function parameter

To pass a string from a function to another function, you can use the address transmission method, that is, using the character array name as a parameter or using a pointer to the string as a parameter. The content of the string can be changed in the called function, and the changed string can be obtained in the main function.

[Example 8.15] use function calls to copy strings.

(1) Using character arrays as parameters

Void copy_string (char from [], Char to [])

{Int I = 0;

While (from [I]! = '\ 0 ')

{To [I] = from [I]; I ++ ;}

To [I] = '\ 0 ';

}

Void main (void)

{Char a [] = "I am a teacher .";

Char B [] = "you are a student .";

Printf ("string_a = % s \ n string_ B = % s \ n", a, B );

Copy_string (A, B );

Printf ("\ nstring_a = % s \ n string_ B = % s \ n", a, B );

}

The program running result is as follows:

String_a = I am a teacher.

String_ B = you are a student.

String_a = I am a teacher.

String_ B = I am a teacher.

A and B are character arrays. The initial value is 8.19 (. The copy_string function assigns from [I] to [I] until the value of from [I] is '\ 0. When the copy_string function is called, The first addresses of A and B are passed to the form and to arrays respectively. Therefore, from [I] And a [I] are the same unit, and to [I] and B [I] are the same unit. After the program is executed, the content of array B is shown in 8.19 (B. It can be seen that, because the original length of array B is greater than array A, the original content of array B cannot be completely overwritten after array a is copied to array B. The last three elements of array B remain unchanged. When B is output, it is output by % s (string). If '\ 0' is reached, the character after the first' \ 0' is not output. If % s format is not used for output, and % C character-by-character output is used, the following characters can be output.

In the main function, character Arrays can also be defined, but pointer variables of character type can be used. The main function can be rewritten as follows:

Void main (void)

{Char * A = "I am a teacher .";

Char * B = "you are a student .";

Printf ("string_a = % s \ n

String_ B = % s \ n ", a, B );

Copy_string (A, B );

Printf ("\ nstring_a = % s \ n

String_ B = % s \ n ", a, B );

}

The running result is the same as that of the preceding program.

(2) Using character pointer variables for parameters

The procedure is as follows:

Void copy_string (char * From, char *)

{

For (; * from! = '\ 0'; from ++, to ++)

* To = * from;

* To = '\ 0 ';

}

Void main (void)

{Char * A = "I am a teacher .";

Char * B = "you are a student .";

Printf ("string_a = % s \ n

String_ B = % s \ n ", a, B );

Copy_string (A, B );

Printf ("\ nstring_a = % s \ n string_ B = % s \ n", a, B );

}

Form and to are character pointer variables. They are equivalent to P1 and P2 in example 8.19.AlgorithmIt is also exactly the same as the example 8.19. When copy_string is called, the first address of array a is sent to from, and the first address of array B is sent. In the for loop in the copy_string function, each time * From is assigned to * To, 1st times is to assign the 1st characters in array A to the 1st characters in array B. After executing from ++ and to ++, from and to point to a [1] and B [1] respectively. Then execute * To = * from to assign a [1] to B [1],.... Finally, assign '\ 0' to * to, and pay attention to the Unit to point.

(3) The copy_string function can also be simplified.

1. Rewrite the copy_string function:

Void copy_string (char * From, char *)

{

While (* To = * From )! = '\ 0 ')

{To ++; from ++ ;}

}

Compare it with the above program. In this program, the "* To = * From;" operation is placed in the while statement expression, and the value assignment operation and the operation to determine whether it is '\ 0' are placed in the expression, assign values first and then judge. In the loop body, to and from value-added point to the next element ,......, Until the value of * From is '\ 0.

2. The function body of the copy_string function can also be changed:

{

While (* To ++ = * From ++ )! = '\ 0 ');

}

Merge the to ++ and from ++ operations of the above program with * To = * from. The execution process is: grant * from to first, then add value to and from. Obviously, this is simplified.

3. The function body can also be written as follows:

{

While (* from! = '\ 0 ')

* To ++ = * From ++;

* To = '\ 0 ';

}

When * from is not '\ 0', assign * from to, and then add value to and from.

Character can use its ASCIICode. For example, "Ch = 'A'" can be replaced by "Ch = 97", "While (Ch! = 'A') "can be used" while (Ch! = 97) "instead. Therefore, "While (* from! = '\ 0') "can be used" while (* from! = 0 ). The relational expression "* from! = 0 "can be simplified to" * from ". This is because if the value of * form is not equal to 0, the expression" * from "is true and" * from! = 0 "is true. Therefore, "While (* from! = 0) "and" while (* From) "are equivalent. Therefore, the function body can be simplified:

{While (* From)

* To ++ = * From ++;

* To = '\ 0 ';}

4. The preceding while statement can be further simplified to the following while statement:

While (* To ++ = * From ++)

It is equivalent to the following statement:

While (* To ++ = * From ++ )! = '\ 0 ');

Assign * from to. If the * to value after the assignment is equal to '\ 0', the loop ends (' \ 0' has been assigned to * ).

5. You can also use the for statement in the while statement in the function body:

For (; (* To ++ = * From ++ )! = 0 ;);

Or for (; * To ++ = * From ;);

6. pointer variables are also available. The copy_string function can be written as follows:

Void copy_string (char from [], Char to [])

{Char * P1, * P2;

P1 = from; P2 =;

While (* P2 ++ = * P1 ++ )! = '\ 0 ');

}

The above usage is changeable and flexible, and the meaning is not intuitive. Beginners may have some difficulties and are prone to errors. However, after being familiar with C, the above forms are used more often. Readers should gradually become familiar with it and master it.

To sum up, as a function parameter, there are the following situations:

Real Parameter

1. Several groups

2. Several groups of character pointer Variables

3. Character pointer variable character pointer variable

4. Number of character pointer Variables

8.4.3 character pointer variables and character Arrays

Although character arrays and character pointer variables can be used to store and operate strings, they are different and should not be confused, mainly including the following:

1. A character array consists of several elements. Each element contains one character, while the character pointer variable stores the address (the first address of the string), which is never placed in the character pointer variable.

2. assign an initial value. To assign an initial value to an array, use the static storage class, as shown in figure

Static STR [] = {"I love China! ");

The character pointer variable does not have to be added with the static storage type, as shown in figure

Char * A = "I love China! ";

This is because the array is not initialized, but the pointer variable is initialized.

3. assign values. Assign values to character arrays only to each element. You cannot assign values to character arrays using the following methods.

Char STR [14];

STR = "I love China! ";

For character pointer variables, you can assign values using the following method:

Char *;

A = "I love China! ";

However, note that A is not a character but the first address of the string.

4. When an initial value is assigned, the following variable definitions and initial values are assigned:

Char * A = "I love China! ";

It is equivalent:

Char *;

A = "I love China! ";

When initializing an array:

Static char STR [14] = {"I love China! "};

Not equivalent

Char STR [14];

STR [] = "I love China! ";

That is to say, an array can assign an overall initial value when the variable is defined, but it cannot assign an integral value in the assignment statement.

5. When defining an array, a memory unit has been allocated during compilation, with a fixed address. When defining a character pointer variable, allocate a memory unit to the pointer variable and place an address value in it. That is to say, the pointer variable can point to a character type data, however, if it is not assigned an address bit, it does not point to any character data. For example:

Char STR [10];

Scanf ("% s", STR );

Yes, but the following method is often used:

Char *;

Scanf ("% s", );

The purpose is to input a string, although it can run normally, but this method is dangerous and should not be promoted. During compilation, although a is assigned to the pointer variable A as a unit, the address of a (that is, & A) is specified, but the value of A is not specified, it is an unpredictable value in unit. Therefore, the scanf function requires that a string be input to the storage zone starting with the value (address) of A (this is a good situation), or it may point to the memory segment of the stored commands or data, this will destroy the program and even cause serious consequences. When the program scale is small, the system can run normally due to a large number of blank areas. When the program scale is large, most of the above "conflicts" are possible. It should be like this:

Char * a, STR [10];

A = STR;

Scanf ("% s", );

First, let a have a definite value, that is, let a point to the beginning of an array, and then enter a string to several units starting from this address.

6. The value of the pointer variable can be changed, for example:

[Example: 8.16]

Void main (void)

{Char * A = "I love China! ";

A = a + 7;

Printf ("% s", );

}

The running result is as follows:

China!

The value of the pointer variable A can be changed. The output string starts from the unit to which a points at that time and ends with '\ 0. Although the array name represents the address, its value cannot be changed. The following is an error:

Char STR [] = {"I love China! "};

STR = STR + 7;

Printf ("% s", STR );

Note: If a pointer variable is defined to point to a string, you can reference the characters in the string referred to by the pointer variable in the form of subscript. For example:

[Example: 8.17]

Void main (void)

{Char * A = "I love China .";

Int I;

Printf ("The Sixth charcter is % C \ n", a [5]);

For (I = 0; A [I]! = '\ 0'; I ++)

Printf ("% C", a [I]);

}

The running result is as follows:

The sixth charcter is E

I love China.

Although array A is not defined in the program, strings are stored in the memory as character arrays. A [5] is executed by * (a + 5), that is, the position of the five elements pointed to by a is moved down, and the value in the unit is taken out.

7. Use Pointer variables to point to a format string, which can be used to replace the format string in the printf function. For example:

Char * format;

Format = "A = % d, B = % F \ n ";

Printf (format, a, B );

It is equivalent

Printf ("A = % d, B = % F \ n", a, B );

Therefore, you only need to change the format of the input and output strings pointed to by the format variable. This printf function is called a variable-format output function.

You can also use character arrays. For example:

Char format [] = "A = % d, B = % F \ n ";

Printf (format, a, B );

However, the assignment statement cannot be used to assign values to the entire array, for example:

Char format [];

Format = "A = % d, B = % F \ n ";

Therefore, it is more convenient to point pointer variables to strings.

Y3 = 1.29

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.