(1)
char* p="how are you ?";
char name[20]="ABCDEFGHIJKLMNOPQRS";
strcpy(name,p);//name改变为"how are you ? OPQRS " ====>错误!
cout << name << endl;
strncpy(name,p,sizeof(name)); //name改变为"how are you ? " ====>正确!
cout << name << endl;
虽然同样输出how are you ?但strcpy后数组name中的内容:
- name 0x0012ff40 "how are you ?" char [20]
[0x0] 0x68 'h' char
[0x1] 0x6f 'o' char
[0x2] 0x77 'w' char
[0x3] 0x20 ' ' char
[0x4] 0x61 'a' char
[0x5] 0x72 'r' char
[0x6] 0x65 'e' char
[0x7] 0x20 ' ' char
[0x8] 0x79 'y' char
[0x9] 0x6f 'o' char
[0xa] 0x75 'u' char
[0xb] 0x20 ' ' char
[0xc] 0x3f '?' char
[0xd] 0x00 char
[0xe] 0x4f 'O' char
[0xf] 0x50 'P' char
[0x10] 0x51 'Q' char
[0x11] 0x52 'R' char
[0x12] 0x53 'S' char
[0x13] 0x00 char
strncpy后数组name中的内容:
- name 0x0012ff40 "how are you ?" char [20]
[0x0] 0x68 'h' char
[0x1] 0x6f 'o' char
[0x2] 0x77 'w' char
[0x3] 0x20 ' ' char
[0x4] 0x61 'a' char
[0x5] 0x72 'r' char
[0x6] 0x65 'e' char
[0x7] 0x20 ' ' char
[0x8] 0x79 'y' char
[0x9] 0x6f 'o' char
[0xa] 0x75 'u' char
[0xb] 0x20 ' ' char
[0xc] 0x3f '?' char
[0xd] 0x00 char
[0xe] 0x00 char
[0xf] 0x00 char
[0x10] 0x00 char
[0x11] 0x00 char
[0x12] 0x00 char
[0x13] 0x00 char
(2)
char* p="how are you ?";
char name[20];
strcpy(name,p); //name改变为"how are you ? 未知字符 " ====>错误!
name[sizeof(name)-1]='/0' //可不要
strncpy(name,p,sizeof(name)); //name改变为"how are you ? " ====>正确!
strcpy后数组name中的内容:
- name 0x0012ff24 "how are you ?" char [20]
[0x0] 0x68 'h' char
[0x1] 0x6f 'o' char
[0x2] 0x77 'w' char
[0x3] 0x20 ' ' char
[0x4] 0x61 'a' char
[0x5] 0x72 'r' char
[0x6] 0x65 'e' char
[0x7] 0x20 ' ' char
[0x8] 0x79 'y' char
[0x9] 0x6f 'o' char
[0xa] 0x75 'u' char
[0xb] 0x20 ' ' char
[0xc] 0x3f '?' char
[0xd] 0x00 char
[0xe] 0xcc char
[0xf] 0xcc char
[0x10] 0xcc char
[0x11] 0xcc char
[0x12] 0xcc char
[0x13] 0xcc char
strncpy后数组name中的内容:
- name 0x0012ff24 "how are you ?" char [20]
[0x0] 0x68 'h' char
[0x1] 0x6f 'o' char
[0x2] 0x77 'w' char
[0x3] 0x20 ' ' char
[0x4] 0x61 'a' char
[0x5] 0x72 'r' char
[0x6] 0x65 'e' char
[0x7] 0x20 ' ' char
[0x8] 0x79 'y' char
[0x9] 0x6f 'o' char
[0xa] 0x75 'u' char
[0xb] 0x20 ' ' char
[0xc] 0x3f '?' char
[0xd] 0x00 char
[0xe] 0x00 char
[0xf] 0x00 char
[0x10] 0x00 char
[0x11] 0x00 char
[0x12] 0x00 char
[0x13] 0x00 char
(3)