2016-05-16 131 views
0

我正在研究将值连接成一串字符的I2C消息系统的C++代码。我的消息正确解决了,但是当我将字符串连接在一起时,代码不正确地将我想要的三个值连接到字符串上。我所编写的代码是下面:在字符串连接期间添加的额外字符

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" 

我的代码似乎在我的人物之间串联一个额外的性格和我不知道在我的上面的代码补充说。我已经通过了代码,一切都应该正常工作,不知道我的问题在哪里。

+1

您允许使用'C++'吗?这(使用cstrings,malloc和cstring函数)当然不是在使用'C++'时做这件事的方法。 – drescherjm

+4

请使用'std :: string'。我求求你。 – erip

+1

你正在使用的所有未定义变量是什么?他们在哪里定义?他们是如何初始化的?当你知道它不能超过'-128'到'127'(或者'0'到'255',取决于'char'的符号)时,你为什么要检查'value1'的大范围?最后,你在哪里免费的''value3'和'value4'? –

回答

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