C++将字符从静态数组复制到动态数组会添加一堆随机元素

C++ copying chars from static to dynamic array adds a bunch of random elements

本文关键字:数组 元素 随机 一堆 添加 动态 字符 静态 复制 C++      更新时间:2023-10-16

我有一个静态数组,但当将值复制到动态数组时,我会得到一堆填充的废话。我需要得到的动态数组正好是8个字符的

unsigned char cipherText[9]; //Null terminated
cout<<cipherText<<endl;      //outputs = F,ÿi~█ó¡
unsigned char* bytes = new unsigned char[8];  //new dynamic array
//Loop copys each element from static to dynamic array.
for(int x = 0; x < 8; x++)
{       
bytes[x] = cipherText[x];
}
cout<<bytes;     //output: F,ÿi~█ó¡²²²²½½½½½½½½ε■ε■

您需要更新代码以复制空终止符:

unsigned char* bytes = new unsigned char[9];  //new dynamic array
//Loop copys each element from static to dynamic array.
for(int x = 0; x < 9; x++)
{       
bytes[x] = cipherText[x];
}
cout<<bytes;

这是假设cipherText实际上包含一个以null结尾的字符串。

如果你想正确打印C字符串,它需要以null结尾。机器必须知道在哪里停止打印。

为了解决这个问题,将bytes放大一个(9而不是8),为空字符腾出空间,然后将其附加到末尾:

bytes[8] = '';

现在,cout将只读取数组中的前8个字符,之后它将遇到''并停止。

你怎么知道密文是空终止的?简单地定义它不会使它以null终止。