This article mainly records the string related operations, as well as memory four areas
string
There are no string types in C, which is emulated by arrays and can represent strings in two ways
// It is represented by an array, in this case there is an array at the end'\ 0'Char string1[] ="abcd"; Char *string2 ="abcd";
Copy the code
An important thing to know about strings is that string handlers need to include the string.h header. Here are a few commonly used ones
- Strlen gets the length of the string
- STRCMP comparison string
- Strcpy copies the string
- Strncpy copies a specified number of strings
- Strcat string concatenation
- Strncat Concatenates a specified number of strings
- STRSTR Lookup string
- STRCHR searches for characters
- Strtok String splitting
Four memory area
As mentioned earlier, C is a low-level language because it can manipulate memory directly using Pointers. In order to better understand the use of C language, it is necessary to master c language memory model.
C memory is divided into four partitions. Stack area Heap area global area (divided into initialized, uninitialized variables) code area
-
Variables defined in the stack area function are allocated memory in the stack area. Its distribution and release are controlled by the system, without manual release
-
The memory allocated in the heap by malloc must be freed manually by the free function, otherwise the program ends
-
Global area Global variable strings and so on are stored in the global area. Global extents are not released during the program’s run life.
// Hello world is stored in the global area. Strings are constants, as in Java"hello world";
Copy the code
- Code area The location where code is stored
char * testMalloc() {// Allocate 100 bytes of space on heap char * STR = (char *)malloc(100); Hello world strcpy(STR,"hello world"); // returns STR, so that outsiders can manipulate the contents of the heap using the return value of this functionreturn str;
}
int mainChar * STR = () {// return a pointer to an addresstestMalloc(); // Prints the string pointed to by STRprintf("string is %s\n", str);
if(str ! = NULL) {// Free heap memory free(STR); str = NULL; }return 0;
}
Copy the code
Important: Memory allocated on the heap must be freed