C ++中字符的指针 [英] Pointer of a character in C++
问题描述
翻阅书籍,第一行指示行应该向我显示 char变量b 存储位置的地址,对于 int变量a .但是第一个cout语句打印出一个奇怪的'dh ^#',而第二个语句正确打印出一个十六进制值'ox23fd68'.为什么会这样?
Going by the books, the first cout line should print me the address of the location where the char variable b is stored, which seems to be the case for the int variable a too. But the first cout statement prints out an odd 'dh^#' while the second statement correctly prints a hex value ' ox23fd68'. Why is this happening?
#include<iostream>
using namespace std;
int main()
{
char b='d';
int a=10;
char *c=new char[10];
c=&b;
int *e=&a;
cout<<"c: "<<c<<endl;
cout<<"e: "<<e;
}
推荐答案
实际上,该程序有问题.内存泄漏.
Actually this program has problem. There is a memory leak.
char *c=new char[10];
c=&b;
这会在堆上分配10个字符,但是指向堆的指针会被变量 b
的地址覆盖.
This allocates 10 characters on heap, but then the pointer to heap is overwritten with the address of the variable b
.
当使用 operator<<
将 char *
写入 cout
时,则将其视为空终止的C字符串.随着b的地址被初始化为包含 d
op<<
的单个字符,继续在堆栈中搜索找到第一个空字符.看来是在几个字符之后找到的,所以写了 dh ^#
( d
是变量 b
的值,其余的是只是在第一个 \ 0
char之前在堆栈上找到的一些随机字符).
When a char*
is written to cout
with operator<<
then it is considered as a null terminated C-string. As the address of b was initialized to a single character containing d
op<<
continues to search on the stack finding the first null character. It seems the it was found after a few characters, so dh^#
is written (the d
is the value of variable b
the rest is just some random characters found on the stack before the 1st \0
char).
如果要获取地址,请尝试使用 static_cast< void *>(c)
.
If you want to get the address try to use static_cast<void*>(c)
.
我的例子:
int main() {
char *c;
char b = 'd';
c = &b;
cout << c << ", " << static_cast<void*>(c) << endl;
}
输出:
dÌÿÿ, 0xffffcc07
看到'd'之后的奇怪字符.
See the strange characters after 'd'.
我希望这可以有所帮助!
I hope this could help a bit!
这篇关于C ++中字符的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!