Home > php教程 > PHP开发 > body text

Detailed explanation of the use of character arrays and strings in C language

高洛峰
Release: 2016-12-12 17:17:35
Original
1430 people have browsed it

1. Definition and initialization of character array
The easiest way to understand the initialization of character array is to assign characters to each element in the array one by one.
char str[10]={ 'I',' ','a','m',' ','h','a','p','p','y'};
That's it The 10 characters are assigned to the 10 elements from str[0] to str[9] respectively. If the number of characters provided in the curly braces is greater than the array length, it will be treated as a syntax error; if it is less than the array length, only these characters will be included in the array. For the first elements, the remaining elements are automatically set to empty characters (i.e. '

3. String representation
In C language, you can use two methods to represent and store strings:
(1) Use a character array to store a string
    char str[ ]="I love China";
( 2) Use a character pointer to point to a string
    char* str="I love China";
For the second representation method, some people think that str is a string variable, and they think that the string constant "I love China" should be directly defined when defining it. Assigning to the string variable is incorrect.
C language handles string constants as character arrays. A character array is opened in the memory to store string constants. When the program defines the string pointer variable str, it only changes the first address of the string (that is, the address where the string is stored). The first address of the character array) is assigned to str.
String output in both representation methods uses
printf("%sn",str);
%s means outputting a string, giving the character pointer variable name str (for the first representation method, the character array name is is the first address of the character array, which is consistent with the meaning of the pointer in the second type), the system first outputs the character data it points to, and then automatically adds 1 to str to point to the next character..., This continues until the end-of-string identifier "

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template