Understanding the Difference: char vs char string
When declaring null-terminated strings in C , the format of the declaration can raise questions. The options are "char string" or "char string." To understand the difference, let's delve into each declaration:
"char* string":
In this declaration, "string" is a pointer to a character. It indicates that "string" holds the address of a character. Essentially, "string" itself is not a character but a pointer pointing to a memory location that stores a character.
"char *string":
Contrary to the previous declaration, here "string" is a single character. The declaration implies that "string" is a character in its own right, not a pointer to a character.
Based on these distinctions, it becomes evident that "char* string" is the more appropriate declaration because it accurately represents the nature of the object as a pointer to a character.
Why the Latter Format is Commonly Seen:
Although "char string" makes more logical sense, the conventional format "char string" is often observed. This practice stems from a potential issue in declaring multiple variables in a single line. Consider the following snippet:
char* string1, string2;
This declaration can lead to ambiguity as it is unclear whether "string2" is also a pointer or a single character. To avoid such confusion, it is generally accepted to use "char string" when declaring multiple variables, reserving "char string" for individual pointer declarations.
The above is the detailed content of What is the difference between `char* string` and `char *string` in C ?. For more information, please follow other related articles on the PHP Chinese website!