了解字符数组初始化和数据存储

Understanding Character array initialization and data storing

本文关键字:数据 存储 初始化 字符 数组 了解      更新时间:2023-10-16

我正在尝试了解字符阵列的初始化以及如何存储数据。

我进行了测试,这就是它的进行

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

我不了解 onetwo的包含比大小本身更多的字符,当我为变量做sizeof时,它们都被证明为 2,就像它是初始化的大小一样。

,如果这样完成了cout

for (int i = 0; i < 6; i++)
{
    cout << testptr->one[i] << endl;
}

结果是:

h
e
l
l
o

如果我走的时间超过6,它将是空的或垃圾。

我知道我可以使用 memcpy很好地分配数量,但是我试图了解固定尺寸的字符数组如何存储它可以保存的东西。

当您 reinterpret_castchar[]struct*时,指向onetwothree在输入字符串中分别指向0th,第二和第4个字符(自从两个差距(每个变量的大小为两个,因此类似ptrptr + 2ptr + 2 + 2(。

h e l l o
^   ^   ^
|   |   |
0   2   4

另外,C 中的char*由NULL字符(''(终止。因此,当您打印onetwothree的值时,我们会看到从开始到遇到结束的所有字符。

而不是使用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