I am working on a C++ code that concatenates values together into a string of chars for an I2C message system. I have the messaging properly worked out, but when I concatenate the strings together, the code incorrectly concatenates more than just the three values I want onto the string. The code I have written is below:
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; } This function has the input of:
concatint(5, ' ', ' '); where the two address values are two ASCii characters.
The result of this code should be: ' '' '5 with the ASCii characters being concatenated before the value. However, when I run the code, the result I get is:
" \005 \0055" My code seems to concatenate an extra character in between my characters and I am not sure where my above code adds that. I've stepped through the code and everything should work fine, not sure where my problem is.
c++? This (using cstrings, malloc and cstring functions) is certainly not the way to do this when usingc++.std::string. I beg you.value1when you know it can't be more than-128to127(or0to255, depending on the signedness ofchar)? And lastly, where do youfreevalue3andvalue4?