字符串串联过程中添加的额外字符
Extra characters added during string concatenation
我正在编写一个C++代码,该代码将值连接到I2C消息系统的字符串中。我已经正确地处理了消息传递,但当我将字符串连接在一起时,代码错误地将不止我想要的三个值连接到字符串上。我写的代码如下:
void concatint(int value1, char address1, char address2)
{
int alive1 = static_cast<int>(address1);
int alive2 = static_cast<int>(address2);
char* alive3 = (char*)malloc(sizeof(address1));
char* alive4 = (char*)malloc(sizeof(address2));
//alive3 = address1;
//alive4 = address2;
sprintf(alive3, "%2d", address1);
sprintf(alive4, "%2d", address2);
if (value1 < 10)
readlength = 1;
if (value1 >= 10 && value1 < 100)
readlength = 2;
if (value1 >= 100 && value1 < 1000)
readlength = 3;
if (value1 >= 1000 && value1 < 10000)
readlength = 4;
if (value1 >= 10000 && value1 < 100000)
readlength = 5;
if (value1 >= 100000 && value1 < 1000000)
readlength = 6;
if (value1 >= 1000000 && value1 < 10000000)
readlength = 7;
if (value1 >= 10000000 && value1 < 100000000)
readlength = 8;
*writedata = 0;
itoa(value1, writedata, 10);
strcpy(writeaddress, &address1);
strcat(writeaddress, &address2);
strcat(writeaddress, writedata);
strcpy(readaddress, address1);
strcat(readaddress, address2);
typevalue = 1;
}
此功能的输入为:
concatint(5, ' ', ' ');
其中两个地址值是两个ASCii字符。
此代码的结果应该是:"5,ASCii字符连接在值之前。然而,当我运行代码时,得到的结果是:
" 05 055"
我的代码似乎在字符之间连接了一个额外的字符,我不确定上面的代码在哪里添加了这个字符。我已经逐步完成了代码,一切都应该正常,不确定我的问题在哪里。
前八行有未定义的行为:
void concatint(int value1, char address1, char address2)
{
int alive1 = static_cast<int>(address1);
int alive2 = static_cast<int>(address2);
// Note that address1 is a char, not a char*, and as such sizeof(address1)
// is guaranteed to be 1. Thus we allocate one byte of storage.
char * alive3 = (char*) malloc(sizeof(address1));
char * alive4 = (char*) malloc(sizeof(address2));
// Here we write two digits and a terminating NUL to that one byte
// => undefined behaviour. Cannot reason further about the program.
sprintf(alive3, "%2d", address1);
sprintf(alive4, "%2d", address2);
此外:
strcpy(writeaddress, &address1);
也不行。address1
是单个字符。&address1
是指向该字符的指针,但后面没有尾随的NUL字符,因此它也不是传递给strcpy
的有效指针。
使用std::string
相关文章:
- 只能向C++添加一定数量的字符
- 如何在C++中为字符串添加字符?
- 如何将字符添加到已经大小的数组中?
- 向字符串添加字符
- 如何编写模板函数来添加整数但连接字符串和字符类型?
- 在字符串中的字符前添加空格C++插入函数
- std::字符串添加到字符*
- Qt UTF-8 文件到 std::string 添加额外的字符
- 编译器将随机字符添加到我的 char 数组中
- 为什么编译器不抱怨将字符添加到 char*?
- 将作为数学运算符的字符添加到随机字符串中
- 将字符添加到 std::cin
- 如何将点字符添加到字符串中的字符
- strftime 将不需要的字符添加到我尝试显示的内容中
- 当我将字符添加到空字符串(如 " " + c)时,为什么要返回未知值?
- 如何将字符添加到 2D 数组
- 将空格字符添加到附加的每个项目,以必须擦除最后一个项目.如何改进
- "b"作为字符添加到字符串中
- 如何将字符添加到字符串中
- C++将x个字符添加到字符串数组中