totn C Functions

C Language: strncpy function
(Bounded String Copy)

In the C Programming Language, the strncpy function copies the first n characters of the array pointed to by s2 into the array pointed to by s1. It returns a pointer to the destination.

If the strncpy function encounters a null character in s2, the function will add null characters to s1 until n characters have been written.

Syntax

The syntax for the strncpy function in the C Language is:

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

Parameters or Arguments

s1
An array where s2 will be copied to.
s2
The string to be copied.
n
The number of characters to copy.

Returns

The strncpy function returns s1.

Required Header

In the C Language, the required header for the strncpy function is:

#include <string.h>

Applies To

In the C Language, the strncpy function can be used in the following versions:

  • ANSI/ISO 9899-1990

strncpy Example

Let's look at an example to see how you would use the strncpy function in a C program:

/* Example using strncpy by TechOnTheNet.com */

#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[])
{
    /* Create an example variable capable of holding 50 characters */
    char example[50];

    /* Copy 16 characters into the example variable
     from the string "TechOnTheNet.com knows strncpy" */
    strncpy (example, "TechOnTheNet.com knows strncpy!", 16);

    /* Add the required NULL to terminate the copied string */
    /* strncpy does not do this for you! */
    example[16] = '\0';

    /* Display the contents of the example variable to the screen */
    printf("%s\n", example);

    return 0;
}

When compiled and run, this application will output:

TechOnTheNet.com

Similar Functions

Other C functions that are similar to the strncpy function: