如下测试:

#include <iostream>
#include <string.h>

using namespace std;

int main() {
    char a[]="123123";
    cout<<strlen(a)<<endl;
    cout<<sizeof(a)<<endl;
    char b[100] = "123123";
    cout<<strlen(b)<<endl;
    cout<<sizeof(b)<<endl;
}

结果是:

6
7
6
100
 

strcpy在拷贝字符串的时候,会把src最后的'\0'也复制过去。

在进行网络数据收发的时候,尤其是使用tcp协议时需要特别注意。因为在tcp基础上,我们往往会先传数据长度,这时候用sizeof和strlen来获取字符串长度是有差别的,会导致程序行为异常。

 

相关文章:

  • 2021-10-17
  • 2021-06-03
  • 2021-11-14
  • 2022-12-23
  • 2022-12-23
  • 2021-06-08
  • 2022-02-20
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-31
  • 2021-07-14
  • 2021-09-01
相关资源
相似解决方案