strncpy ()- Zeichenfolgen kopieren

Format

#include <string.h>
char *strncpy(char *string1, const char *string2, size_t count);

Sprachniveau

ANSI

Sicher für Threads

Ja

Beschreibung

Die Funktion strncpy() kopiert count Zeichen von string2 nach string1. Wenn count kleiner-gleich der Länge von string2ist, wird ein Nullzeichen (\0) nicht an die kopierte Zeichenfolge angehängt. Wenn Anzahl größer als die Länge von string2ist, wird das Ergebnis string1 mit Nullzeichen (\0) bis zur Länge Anzahlaufgefüllt.

Rückgabewert

Die Funktion strncpy() gibt einen Zeiger auf string1zurück.

Beispiel

Dieses Beispiel veranschaulicht den Unterschied zwischen strcpy() und strncpy().
#include <stdio.h>
#include <string.h>
 
#define SIZE    40
 
int main(void)
{
  char source[ SIZE ] = "123456789";
  char source1[ SIZE ] = "123456789";
  char destination[ SIZE ] = "abcdefg";
  char destination1[ SIZE ] = "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, destination 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 );
}
 
/*****************  Output should be similar to:  *****************
 
destination is originally = 'abcdefg'
After strcpy, destination becomes '123456789'
 
destination1 is originally = 'abcdefg'
After strncpy, destination1 becomes '12345fg'
*/

Zugehörige Informationen