将字符数组转换为结构时出现问题. 结构的字符数组变量溢出

Issue with converting char array to structure. char array variable of structure gets overflow

本文关键字:结构 数组 字符 问题 溢出 变量 转换      更新时间:2023-10-16

我想将字符数组转换为结构,但在打印时我得到以下输出

输出:测试世界(在第 1 行中( st 世界(第 2 行(

#pragma(1)
struct MyStruct
{
char a[2];
char b[5];
};
int main()
{
char test[11] = "Test World";
char *c = test;
struct MyStruct *Test = (MyStruct*)(c);
cout << Test->a << endl;
cout << Test->b;
cin.ignore();
return 0;
}

我希望根据结构变量的大小输出。 我的预期输出:Te(在第 1 行( 新禾(第2行(

你的程序有几个问题。

首先,通过不指向MyStruct(也不兼容(对象的MyStruct指针进行间接操作。因此,程序的行为是未定义的。

其次,字符串Te根本不适合MyStruct::a,因为没有足够的空间。字符串Te包含三个字符,MyStruct::a仅为 2。只有字符Te合适,但没有空间容纳 null 终止符字符,因此它不能是以 null 结尾的字符串。同样的问题是你对适合MyStruct::b的期望。

也许您的意图是没有以 null 结尾的字符串,但您的问题是您将非 null 终止的字符数组插入到标准流std::cout中,这要求参数是以 null 结尾的字符串。由于违反此要求,程序的行为将未定义。

下面是一个可能的代码片段,它将具有明确定义的行为并具有所需的输出:

MyStruct Test;
std::memcpy(&Test, test, sizeof Test);
for(char c : Test.a)
std::cout << c;
std::cout << 'n';
for(char c : Test.b)
std::cout << c;

C strin 为零端接。因此,您需要在结构的字段中添加终止零。https://godbolt.org/z/kfsioP

struct MyStruct
{
char a[2];
char b[5];
};
int main()
{
char test[11] = "Test World";
char *c = test;
struct MyStruct *Test = (MyStruct*)(c);
Test -> a[sizeof(Test -> a) - 1] = 0;
Test -> b[sizeof(Test -> b) - 1] = 0;
std::cout << Test->a << std::endl;
std::cout << Test->b;
return 0;
}