What is a char*
, exactly? Is it a pointer? I thought pointers had the ast开发者_如何学运维erisk before the identifier, not the type (which isn't necessarily the same thing)...?
It is a pointer to a char
.
When declaring a pointer, the asterisk goes after the type and before the identifier, with whitespace being insignificant. These all declare char
pointers:
char *pointer1;
char* pointer2;
char * pointer3;
char*pointer4; // This is illegible, but legal!
To make things even more confusing, when declaring multiple variables at once, the asterisk only applies to a single identifier (on its right). E.g.:
char* foo, bar; // foo is a pointer to a char, but bar is just a char
It is primarily for this reason that the asterisk is conventionally placed immediately adjacent to the identifier and not the type, as it avoids this confusing declaration.
It is a pointer to a character. You can write either
char* bla;
or
char *bla;
It is the same.
Now, in C, a pointer to a char was used for strings: The first character of the string would be where the pointer points to, the next character in the address that comes next, etc. etc. until the Null-Terminal-Symbol \0
was reached.
BUT: There is no need to do this in C++ anymore. Use std::string (or similar classes) instead. The char* stuff has been named the single most frequent source for security bugs!
http://cplusplus.com/doc/tutorial/pointers/
The *
character shows up in two distinct places when dealing with pointers. First, the type "pointer to T" is denoted by T*
(appending *
to the type name). Second, when dereferencing a pointer, which is done by prepending *
to the name of the pointer variable that you want to dereference.
Whitespace doesn't normally matter, so
char* suchandsuch;
char *suchandsuch;
char
*
suchandsuch;
are all the same.
精彩评论