i`m trying to concatenate a characters using memcpy function, however, i kinda get a weird length of my buffer after couple of memcpy. please see code below
int main()
{
uint8 txbuffer[13]={0};
uint8 uibuffer[4] = "abc";
uint8 rxbuffer[4] = "def";
uint8 l[2]="g";
int index = 1;
cout << strlen((char*)txbuffer) <<endl;
memcpy(&txbuffer[1],&uibuffer, strlen((char*)uibuffer));
index+=strlen((char*)uibuffer);
cout <<"after first memcpy: "<< strlen((char*)txbuffer) <<endl;
memcpy(&txbuffer[index],&rxbuffer, strlen((char*)uibuffer));
cout <<"after second memcpy: "<< strlen((char*)txbuffer) <<endl;
memcpy(&txbuffer[0],&l, strlen((char*)l));
cout <<"after third memcpy: "<< strlen((char*)txbuffer) <<endl;
for (int i = 0; i < sizeof(txbuffer); i += 1)
{
cout << (int(txbuffer[i]))<<" : "<< char(int(txbuffer[i]))<<endl;
}
return 0;
}
the output is:
after first memcpy: 0
after second memcpy: 0
after third memcpy: 7
103 : g
97 : a
98 : b
99 : c
100 : d
101 : e
102 : f
0 :
0 :
0 :
0 :
0 :
0 :
my question is why after the first memcpy, the strlen of the buffer still is zero?
This is because the first character in
txbufferis the null character\0. (You initialized it this way.) So the string effectively has zero-length when you print it out.You didn’t overwrite the first character in the first or second copies. But you finally do overwrite it in the 3rd copy. That’s why the length is zero until after the 3rd copy.