【发布时间】:2017-09-12 17:52:07
【问题描述】:
我试图了解字符数组是如何初始化的以及数据是如何存储的。
我做了一个测试,结果是这样的
struct test
{
char one [2];
char two [2];
char three[2];
};
test * testptr;
char testchar[] = "hello";
testptr = reinterpret_cast<test*>(testchar);
cout << testptr->one << endl;
cout << testptr->two << endl;
cout << testptr->three << endl;
我期待看到类似的东西:
he
ll
o
但是,当我编译时,我得到:
hello
llo
o
我不明白 one 和 two 包含比大小本身更多的字符,当我为变量执行 sizeof 时,它们都变成了 2,就像它的大小一样已初始化。
如果完成了这样的cout:
for (int i = 0; i < 6; i++)
{
cout << testptr->one[i] << endl;
}
结果是:
h
e
l
l
o
如果我超过6,它要么是空的,要么是垃圾。
我知道我可以使用memcpy 很好地将数量字节分配到数组中,但我试图了解固定大小的字符数组如何能够存储比它所能容纳的更多的内容。
【问题讨论】:
标签: c++ arrays char reinterpret-cast