C++ 什么是`char*`?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4293670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a `char*`?
提问by Maxpm
What is a char*
, exactly? Is it a pointer? I thought pointers had the asterisk before the identifier, not the type (which isn't necessarily the same thing)...?
什么是char*
,究竟是什么?是指针吗?我认为指针在标识符之前有星号,而不是类型(不一定是同一件事)......?
回答by Cameron
It is a pointer to a char
.
它是一个指向 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
指针:
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.
主要是因为这个原因,星号通常紧邻标识符而不是类型,因为它避免了这种混淆的声明。
回答by Lagerbaer
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.
现在,在 C 中,一个指向 char 的指针用于字符串:字符串的第一个字符将是指针指向的位置,地址中的下一个字符,等等,直到 Null-Terminal-Symbol\0
达到了。
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!
但是:不再需要在 C++ 中执行此操作。改用 std::string (或类似的类)。char* 内容已被命名为安全漏洞的最常见来源!
回答by suszterpatt
http://cplusplus.com/doc/tutorial/pointers/
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.
*
处理指针时,字符出现在两个不同的地方。首先,类型“指向 T 的指针”由T*
(附加*
到类型名称)表示。其次,当取消引用一个指针时,这是通过*
在要取消引用的指针变量的名称前面添加来完成的。
回答by Pizearke
Whitespace doesn't normally matter, so
空格通常无关紧要,所以
char* suchandsuch;
char *suchandsuch;
char
*
suchandsuch;
are all the same.
都是一样的。