The strncpy () function in C

Strncpy char * (char * dest, const char * src, size_t n) copies up to n copies to n characters from the string pointed to by src to dest. In case the length of the src is smaller than n, the remainder or the remainder of dest will be filled with null values.

Strncpy char * (char * dest, const char * src, size_t n) copies up to n copies to n characters from the string pointed to by src to dest. In case the length of the src is smaller than n, the remainder or the remainder of dest will be filled with null values.

Declaring strncpy () function in C

Here is the declaration for strncpy () in C:

 char * strncpy ( char * dest , const char * src , size_t n ) 

Parameters

dest - This is the pointer to the destination array, where the content is copied.

src - The string is copied.

n - Number signed me to be copied from src.

Returns the value

This function returns the last copy of the copied string.

For example

The following program C illustrates the usage of strncpy () function. Here we have used the memset () function to clear the memory location.

 #include #include int main () { char src [ 40 ]; char dest [ 12 ]; memset ( dest , '' , sizeof ( dest )); strcpy ( src , "Hoc C co ban va nang cao tai QTM !!!" ); strncpy ( dest , src , 10 ); printf ( "Sau khi thuc hien ham strncpy, chuoi dest co dang: n%sn" , dest ); return ( 0 ); } 

Compiling and running the above C program will result:

The strncpy () function in C Picture 1The strncpy () function in C Picture 1

According to Tutorialspoint

Previous lesson: strcpy () function in C

Next lesson: strcspn () function in C

4 ★ | 3 Vote