Your Browser is not longer supported

Please use Google Chrome, Mozilla Firefox or Microsoft Edge to view the page correctly
Loading...

{{viewport.spaceProperty.prod}}

strncpy - Copy string

&pagelevel(4)&pagelevel

Definition    

#include <string.h>

char *strncpy(char *s1, const char *s2, size_t n);

strncpy copies a maximum of n characters from string s2 to string s1.

If string s2 contains fewer than n characters, only the length of s2 (strlen + 1) will be copied.

If string s2 contains n or more characters (excluding the null byte), string s1 is not automatically terminated with the null byte.

If string s1 contains more than n characters and the last character copied from s2 is not the null byte, any data which may still remain in s1 is retained.

Return val.

Pointer to the result string s1.

strncpy does not automatically terminate s1 with the null byte.

Notes

strncpy does not check whether s1 is large enough for the result!

Since strncpy does not automatically terminate the result string with the null byte, it may often be necessary to explicitly terminate s1 with a null byte. This is the case, for example, when only a segment of s2 is being copied and s2 does not contain a null byte either.

The behavior is undefined if memory areas overlap.

Example 1

The following program fragment copies the entire string s2 to string s1 (like the strcpy function). 

#include <stdio.h>
#include <string.h>
int main(void)
{
    int n;
    char s1[20];
    char s2[20];
    printf("Please enter s2 (max. 19 characters)\n");
    scanf("%s", s2);
    printf("s1: %s\n", strncpy(s1, s2, (strlen(s2) + 1)));
    return 0;
}

Example 2

This program copies only a segment (8 characters) of s2 to s1. The result string is explicitly terminated with the null byte.

#include <stdio.h>
#include <string.h>
int main(void)
{
  char *s1 = "                         ";
  char *s2 = "Peter is going swimming !";
  strncpy(s1, s2, 8);
  *(s1 + 8) = '\0';
  printf("s1: %s\n", s1);    /* Contents of s1: "Peter is" */
  return 0;
}

Example 3

In this example, only a segment (5 characters) of s2 is copied to s1. The remaining data in s1 is retained.

#include <stdio.h>
#include <string.h>
int main(void)
{
  char *s1 = "James is going shopping !";
  char *s2 = "Peter is going swimming !";
  strncpy(s1, s2, 5);
  printf("s1: %s\n", s1);    /* Contents of s1: "Peter is going
                                   shopping !" */
  return 0;
}

See also

strcpy, strlen