我正在研究一种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字符在值之前连接。但是,当我运行代码时,我得到的结果是:
" \005 \0055"
我的代码似乎在我的角色之间连接了一个额外的角色,我不确定我上面的代码在哪里添加。我已经完成了代码,一切都应该正常,不确定我的问题在哪里。
答案 0 :(得分:4)
前八行有未定义的行为:
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