C String Functions - C strncpy






char *strncpy(char *str1 , const char *str2 , size_t n );

Copies up to n characters from the string pointed to by str2 to str1.

Copying stops when n characters are copied or the terminating null character in str2 is reached.

If the null character is reached, the null characters are continually copied to str1 until n characters have been copied.

Prototype

char * strncpy ( char * destination, const char * source, size_t num );

Parameter

This function has the following parameter.

destination
Pointer to the destination array.
source
C string to be copied.
num
Maximum number of characters to be copied from source.

size_t is an unsigned integral type.

Return

destination is returned.

Example


#include <stdio.h>
#include <string.h>
//from w  ww . ja  v  a 2 s.c  o  m
int main (){
  char str1[]= "To be or not to be";
  char str2[40];
  char str3[40];

  /* copy to sized buffer (overflow safe): */
  strncpy ( str2, str1, sizeof(str2) );

  /* partial copy (only 5 chars): */
  strncpy ( str3, str2, 5 );
  str3[5] = '\0';   /* null character manually added */

  puts (str1);
  puts (str2);
  puts (str3);

  return 0;
} 

       

The code above generates the following result.





Example 2


#include <string.h>
#include <stdio.h>
#include <stdlib.h>
 /*from w ww  .ja v  a  2s .com*/
int main(void){
    char src[] = "hi";
    char dest[6] = "abcdef"; // no null terminator
    strncpy(dest, src, 5);
    for(size_t n = 0; n < sizeof dest; ++n) {
        char c = dest[n];
        c ? printf("'%c' ", c) : printf("'\\0' ");
    }
 
    char dest2[2];
    strncpy(dest2, src, 2);
    for(size_t n = 0; n < sizeof dest2; ++n) {
        char c = dest2[n];
        c ? printf("'%c' ", c) : printf("'\\0' ");
    }
}

The code above generates the following result.