gpt4 book ai didi

c++ - 在 C++ 中的 memcpy 之后得到 strlen

转载 作者:行者123 更新时间:2023-11-30 03:04:52 24 4
gpt4 key购买 nike

我正在尝试使用 memcpy 函数连接字符,但是,在几个 memcpy 之后,我的缓冲区长度有点奇怪。请看下面的代码

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;
}

输出是:

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 :

我的问题是为什么在第一次 memcpy 之后,缓冲区的 strlen 仍然为零?

最佳答案

memcpying strlen 字节后,你不应该 strlen 目的地,因为你没有复制 0 终止符。

此外,您从字节 1 而不是 0 开始复制,这意味着 strlen 为 0,因为您的数组最初为零(这让我的第一段变得无关紧要,但您应该意识到这一点).

关于c++ - 在 C++ 中的 memcpy 之后得到 strlen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8262406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com