How to store C language strings in an array.
There are two common ways to store strings in character arrays in the C language.
- Initialize a string using a character array.
char str[] = "Hello, World!";
In this case, the compiler will automatically allocate enough memory for the character array to store the entire string, and add a null character ‘\0’ at the end to indicate the end of the string.
- Assigning strings one character at a time using a character array.
char str[14]; // 需要预先定义足够的内存来存储字符串(包括末尾的空字符 '\0')
str[0] = 'H';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = ',';
str[6] = ' ';
str[7] = 'W';
str[8] = 'o';
str[9] = 'r';
str[10] = 'l';
str[11] = 'd';
str[12] = '!';
str[13] = '\0';
In this method, it is necessary to predefine the length of a character array, assign values to each element one by one, and manually add a null character ‘\0’ at the end to indicate the end of the string.
Whichever method used, it is important to ensure that the character array is long enough to store the entire string, including the null character ‘\0’ at the end. If the character array is not long enough, it may lead to issues such as string truncation or memory overflow.