Home >Backend Development >C++ >What\'s the Difference between `char*` and `char[]` in C?
Understanding the Distinction between char* and char[]
When dealing with character arrays and pointers in C programming, it's crucial to grasp the fundamental differences between char str[] = "Test"; and char *str = "Test";.
char str[] = "Test";
In this declaration, str represents an array of characters (chars) with a fixed size, initialized with the contents of the string "Test". The array owns its own memory and is distinct from the original string literal. Any modifications to str will alter the local copy of the data, not the "Test" string itself.
char *str = "Test";
Here, str is a pointer, specifically a pointer to the first character of the string literal "Test". The pointer stores the memory address of this character. However, it's crucial to remember that str does not own the memory where the string is stored; instead, it points to the read-only (const) string literal. Consequently, any attempt to change the string pointed to by str will result in undefined behavior.
Key Differences:
The above is the detailed content of What\'s the Difference between `char*` and `char[]` in C?. For more information, please follow other related articles on the PHP Chinese website!