编辑:我已经为示例添加了源。
我遇到了这个例子:
char source[MAX] = "123456789";
char source1[MAX] = "123456789";
char destination[MAX] = "abcdefg";
char destination1[MAX] = "abcdefg";
char *return_string;
int index = 5;
/* This is how strcpy works */
printf("destination is originally = '%s'\n", destination);
return_string = strcpy(destination, source);
printf("after strcpy, dest becomes '%s'\n\n", destination);
/* This is how strncpy works */
printf( "destination1 is originally = '%s'\n", destination1 );
return_string = strncpy( destination1, source1, index );
printf( "After strncpy, destination1 becomes '%s'\n", destination1 );
产生此输出的内容:
目的地最初是='abcdefg' 在strcpy之后,目标变为“ 123456789” destination1最初是='abcdefg' 在strncpy之后,destination1变为'12345fg'
这使我想知道为什么有人会想要这种效果。看起来会令人困惑。该程序使我认为您基本上可以使用Tom Bro763复制某人的名字(例如Tom Brokaw)。
使用 strncpy()
over有 strcpy()
什么优点?
strcpy
代替strncpy
?”