strcpy:
strcpy(str1, str2);
将从str2开始到结束符(包括)的字符串复制到从str1开始的地址
strncpy:
strncpy(str1,str2,n);
将从str2开始n个字符复制到str1开始的地址
1.
int main()
{
char str[] = "abcde\0";
char str1[] = "gggggggggggg\0";
char str2[] = "gggggggggggg\0";
strcpy(str1, str);
strncpy(str2, str, strlen(str));
printf("strcpy:str1[%s]\nstrncpy:str2[%s]\n", str1, str2);
return 0;
}
./test
strcpy:str1[abcde]
strncpy:str2[abcdeggggggg]
2.
int main()
{
char str[] = "abc e\0";
char str1[] = "gggggggggggg\0";
char str2[] = "gggggggggggg\0";
strcpy(str1, str);
strncpy(str2, str, strlen(str));
printf("strcpy:str1[%s]\nstrncpy:str2[%s]\n", str1, str2);
return 0;
}
./test
strcpy:str1[abc e]
strncpy:str2[abc eggggggg]
3.
int main()
{
char str[] = "abcdeabcdeabcdeabcde\0";
char str1[] = "gggggggggggg\0";
char str2[] = "gggggggggggg\0";
strcpy(str1, str);
strncpy(str2, str, strlen(str));
printf("strcpy:str1[%s]\nstrncpy:str2[%s]\n", str1, str2);
return 0;
}
./test
strcpy:str1[abcdeabcdeabcdeabcde]
strncpy:str2[bcdegggggggg]
4.
int main()
{
char str[] = "abcdeabcdeabcdeabcdesdflakfjkddddddddddddddddddddddddddddddddddddddddddddddd";
char str1[] = "gggggggggggg";
char str2[] = "gggggggggggg";
strcpy(str1, str);
strncpy(str2, str, strlen(str2));
printf("size:\nstr:%d\nstr1:%d\nstr2:%d\n", sizeof(str), sizeof(str1), sizeof(str2));
printf("strcpy:str1[%s]\nstrncpy:str2[%s]\nstr[%s]\n", str1, str2, str);
return 0;
}
./test
size:
str:77
str1:13
str2:13
strcpy:str1[abcdeabcdeabcdeabcdesdflakfjkddddddddddddddddddddddddddddddddddddddddddddddd]
strncpy:str2[bcdesdflakfj]
str[bcdesdflakfjkddddddddddddddddddddddddddddddddddddddddddddddd]
str地址变了,是由于str目标地址不够造成的吗?
5.
int main()
{
char str[] = "abcdeabcdeabcdeabcdesdflakfjkj";
char str1[] = "ggggggggggggddddddddddddddddddddddd";
char str2[] = "gggggggggggg";
strcpy(str1, str);
strncpy(str2, str, strlen(str2));
printf("size:\nstr:%d\nstr1:%d\nstr2:%d\n", sizeof(str), sizeof(str1), sizeof(str2));
printf("strcpy:str1[%s]\nstrncpy:str2[%s]\nstr[%s]\n", str1, str2, str);
return 0;
}
./test
size:
str:31
str1:36
str2:13
strcpy:str1[abcdeabcdeabcdeabcdesdflakfjkj]
strncpy:str2[abcdeabcdeab]
str[abcdeabcdeabcdeabcdesdflakfjkj]
好像是~
6.
int main()
{
char str[] = "abcdeabcdeabcdeabcdesdflakfjkj";
char str1[] = "ggggggggggggddddddddddddddddddddddd";
char str2[] = "gggggggggggg";
strcpy(str1, str);
strncpy(str2, str, strlen(str));
printf("size:\nstr:%d\nstr1:%d\nstr2:%d\n", sizeof(str), sizeof(str1), sizeof(str2));
printf("strcpy:str1[%s]\nstrncpy:str2[%s]\nstr[%s]\n", str1, str2, str);
return 0;
}
./test
size:
str:31
str1:36
str2:13
strcpy:str1[bcdesdflakfjkjeabcdesdflakfjkj]
strncpy:str2[abcdeabcdeabcdeabcdesdflakfjkjeabcdesdflakfjkj]
str[abcdeabcdeabcdeabcdesdflakfjkj]
看来strncpy超出范围也把str地址改了~