[英]Printing out the value of pointer to the first index of an char array
I'm new to C++ and is trying to learn the concept of pointer. 我是C ++的新手,正在尝试学习指针的概念。 When I tried to print out the value of pStart, I was expecting its value to be the address of text[0] in hexdecimal (eg something like 0x7fff509c5a88). 当我尝试打印pStart的值时,我期望它的值是十六进制的text [0]的地址(例如,类似0x7fff509c5a88的地址)。 However, the actual value printed out is abcdef. 但是,打印出的实际值为abcdef。
Could someone explain it to me why this is the case? 有人可以向我解释为什么会这样吗? What parts am I missing? 我缺少什么部分?
char text[] = "abcdef";
char *pStart = &text[0];
cout << "value of pStart: " << pStart << endl;
Iostreams provide an overload that assumes a pointer to char points to a NUL-terminated (C-style) string, and prints out the string it points to. Iostream提供了一个重载,它假定指向char的指针指向以NUL终止(C样式)的字符串,并输出指向的字符串。
To get the address itself to print out, cast it to a pointer to void instead: 为了使地址本身可以打印出来,请将其强制转换为一个指向void的指针:
cout << "value of pStsart: " << (void *)pStart << "\n";
Note that you don't really need pStart
here at all though. 注意,您实际上根本不需要pStart
。 The name of an array (usually, including this case) evaluates to the address of the beginning of the array, so you can just print it directly: 数组的名称(通常包括这种情况)的值等于数组开头的地址,因此您可以直接打印它:
cout << "address of text: " << (void *)text << "\n";
Get out of the habit of using endl
as well. 也要摆脱使用endl
的习惯。 It does things you almost certainly don't realize and almost never want. 它所做的事情几乎是您肯定不会意识到并且几乎从不想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.