How is a string stored in the C language?
In the C language, strings can be stored as character arrays or character pointers. Here are two common methods:
- Character array: Strings can be stored by declaring a fixed-size character array. For example, you can declare a string array containing 10 characters in the following way:
char str[11]; // 包括一个额外的字符来存储字符串的结束符'\0'
Next, you can use a string assignment function (such as strcpy) to store the string in this character array.
strcpy(str, "Hello"); // 将字符串"Hello"复制到str数组中
Please note that the size of the character array must be large enough to accommodate the string and its terminator.
- Character pointer: You can use a character pointer to store strings. For example, you can declare a character pointer and allocate enough memory to store a string like this:
char *str;
str = malloc(6); // 分配6个字节的内存,用于存储字符串"Hello"
Afterward, you can use string assignment functions (such as strcpy) to store the string in the memory pointed to by this character pointer.
strcpy(str, "Hello"); // 将字符串"Hello"复制到str指向的内存中
Remember to free the allocated memory when you no longer need to use the character pointer.
free(str); // 释放str指向的内存
When using character pointers to store strings, it is important to be mindful of memory allocation and deallocation.