C strncpy() Function Tutorial

  • Post author:
  • Post category:C

In this section we will learn what the strncpy() function is and how to use it in C.

C String Copy: strncpy() Function

Sometimes we want to copy a portion of the content of one character-string and place it in another memory location.

This is where we can use the `strncpy` function.

Note: the prototype of this function exists in the `string.h` header file and so we need to include the header file in order to use the function.

strncpy() Function Syntax

Here’s the prototype of the function:

char* strncpy( char* dest, const char* src, size_t count );

strncpy() Function Parameters

  • The first parameter of the function is the address of the memory location that we want to paste the character-string in there.
  • The second parameter is the address of the character-string that we want to copy a portion of its content.
  • The third parameter is the number of characters that we want to copy from the source character-string.

strncpy() Function Return Value

The returned value of the function is the address of the memory location where the character-string are pasted.

Notes:

  • The null `\0` character of the source character-string is copied only if it’s in the range of n-number of characters that should be copied (n is the number of characters that we want to copy from the source of the character-string).
  • If there’s a character-string already in the destination memory-location, only the first n-number of those characters will be replaced by the copied character string. (n is the number of characters that we want to copy from the source of the character-string)

Example: strncpy() in C

#include <stdio.h>
#include <string.h>
int main() {

    char destination[100] = "Hi my name is John Doe";
    char source[] = "Hello to you";

    strncpy(destination, source, 6);

    puts(destination);

    return  0;
}

Output:

Hello name is John Doe

Leave a Reply