Warum sollten Sie strncpy anstelle von strcpy verwenden?

Bearbeiten: Ich habe die Quelle für das Beispiel hinzugefügt.

Ich bin rübergekommendieses Beispiel:

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 );

Was diese Ausgabe hervorgebracht hat:

destination is originally = 'abcdefg'
After strcpy, destination becomes '123456789'

destination1 is originally = 'abcdefg'
After strncpy, destination1 becomes '12345fg'

Was mich wundert, warum irgendjemand diesen Effekt haben möchte. Es sieht so aus, als wäre es verwirrend. Dieses Programm lässt mich denken, dass Sie mit Tom Bro763 im Grunde den Namen von jemandem (z. B. Tom Brokaw) kopieren könnten.

Was sind die Vorteile der Verwendung strncpy() Über strcpy()?

Antworten auf die Frage(10)

Ihre Antwort auf die Frage