memcpy復制字符串的注意事項/memcpy不能用來拷貝類類型


strcpy復制src到dst,最后將dst的下一個位置置為'\0',所以dst是以'\0'結尾的字符串

char c1[10] = "abcde";
cout << c1 << endl;
char *s = c1;
char*end = &c1[9];
printf("%d\n", strlen(c1));// strlen不包括結尾的'\0'長度
printf("%d\n", sizeof(c1));//10個字節
while (s != end)
{
    cout <<int( *s++) << " ";
        
}
char c2[10];//c2的元素默認初始化,值未知
for (auto x : c2)
{
    cout << int(x) << endl;//轉換為int輸出
        
}
3 strcpy(c2, c1);    //memcpy(c2, c1,strlen(c1));
4 for (auto x : c2)
5 {
6     cout <<int( x )<< endl;//轉換為int輸出
7     
8 }
9 cout << strlen(c2) << endl;

但是用memcpy是按字節拷貝,第三個參數不大於strlen(c1)長度,就不會拷貝空字符到尾部,下面這段代碼只拷貝了abcde, '\0'不會被拷貝,strlen(c2)會求出一個錯誤的長度

char c1[10] = "abcde";
char c2[10];//c2的元素默認初始化,值未知
/*strcpy(c2, c1);*/
memcpy(c2, c1,strlen(c1));
for (auto x : c2)
{
    cout <<int( x )<< endl;//轉換為int輸出
        
}
cout << strlen(c2) << endl;

正確的拷貝做法是 memcpy(c2,c1,strlen(c1)+1)

memcpy的拷貝方式是void*dst和void*src都轉換為char*類型的指針,按字節拷貝

memcpy可以用於int,char,struct,數組的拷貝,可以拷貝string類型嗎?

1 int a[10] = { 1, 2, 3, 4, 5, 5, 7, 8, 9, 0 };
2 int *ap = new int[10];
3 memcpy(ap, a, sizeof(a)*sizeof(int));
4 int *endp = ap + 10;
5 while (ap != endp)
6 {
7     cout << *ap++ << " ";
8 
9 }

拷貝結構體

 1 struct {
 2     char name[40];
 3     int age;
 4 } person, person_copy;
 5 
 6 int main()
 7 {
 8     char myname[] = "Pierre de Fermat";
 9 
10     /* using memcpy to copy string: */
11     memcpy(person.name, myname, strlen(myname) + 1);
12     person.age = 46;
13 
14     /* using memcpy to copy structure: */
15     memcpy(&person_copy, &person, sizeof(person));
16 
17     printf("person_copy: %s, %d \n", person_copy.name, person_copy.age);
18 
19     return 0;
20 }

不能拷貝string類型,sizeof(string)只是求了固定大小的成員的內存和,而沒有求string內部指針指向的存字符的那一段內存

如果結構體含有指針,指向某段內存,memcpy的拷貝也會失敗

https://www.2cto.com/kf/201111/110916.html   http://blog.csdn.net/qq_21550341/article/details/51636366

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM