了解字符数组初始化和数据存储
Understanding Character array initialization and data storing
我正在尝试了解字符阵列的初始化以及如何存储数据。
我进行了测试,这就是它的进行
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
很好地分配数量,但是我试图了解固定尺寸的字符数组如何存储它可以保存的东西。
当您 reinterpret_cast
到 char[]
到 struct*
时,指向one
,two
和three
在输入字符串中分别指向0th,第二和第4个字符(自从两个差距(每个变量的大小为两个,因此类似ptr
,ptr + 2
,ptr + 2 + 2
(。
h e l l o
^ ^ ^
| | |
0 2 4
另外,C 中的char*
由NULL字符(' '
(终止。因此,当您打印one
,two
和three
的值时,我们会看到从开始到遇到结束的所有字符。
而不是使用cout,您可以在循环中打印每个char阵列值直到达到您的需求。
#include <string.h>
#include <iostream>
using namespace std;
struct test
{
char one [2];
char two [2];
char three[2];
test()
{
cout<<"in test"<<endl;
memset(&one,NULL,3);
memset(&two,NULL,3);
memset(&three,NULL,3);
}
void display()
{
cout<<" one two three"<<endl;
for(int i=0;i<2;i++)
{
cout<<one[i]<<" "<<two[i]<<" "<<three[i]<<endl;
}
cout<<endl;
}
};
main()
{
test testobj;
test *testptr = &testobj;
char testchar[] = "hello";
testptr->display();
testptr = reinterpret_cast<test*>(testchar);
testptr->display();
cout << testptr->one << endl;
cout << testptr->two << endl;
cout << testptr->three << endl;
}
输出:
在测试中 一两个三个
一两三个
h l o
e l
你好lloo
相关文章:
- 将从格式化文本文件读取的文本数据存储到链表
- 将线程中的数据存储到全局容器的最佳方法?
- 将数据存储在内存中以供以后访问
- 将一个阵列中的数据存储到另外两个阵列中不起作用
- 如何将函数的输出数据存储在文本文件中
- 将结构数据存储在循环缓冲区中
- 安卓中的Qt和应用程序数据存储
- C++ 将数据存储在对齐数组的中间
- 如何删除字符串中的所有空格并将数据存储在两者之间
- 实现双链接列表,其中数据存储在堆上
- 是否有一种方法可以从文本文件中读取并将单个数据存储为不同的变量
- 了解字符数组初始化和数据存储
- 如何在C++中将字符串数据存储在字符串 2D 数组中
- 将数据存储在具有可互换 x/y 坐标的 2D 矩阵中
- 将文件中的数据存储到数组中
- 将数据存储到地图
- 保存和加载类数据存储在C 中的二进制文件中
- 将由结构构建的数组传递到将数据存储到文件中的函数
- 在这种情况下,将数据存储在诸如SQLite之类的数据库中,还是存储在平面文本文件中更好
- 将数据存储在char数组中导致变量周围损坏