+1 vote
in Programming Languages by (8.5k points)
What is the difference between C functions strcpy() and strncpy()? Please give an example.

1 Answer

+3 votes
by (348k points)
edited by
 
Best answer

Both the strcpy() and strncpy() functions copy the contents of a source variable to a destination variable. 

The strcpy() function copies the entire contents of the source string to the destination string. 

The strncpy() function copies a specified number of characters from the source string to the destination string. If the specified number of characters to copy is greater than the length of the source string, the destination string is padded with null characters.

Here is an example:

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

int main() {
char source[] = "New to C programming";
char dest1[20];
char dest2[20];

strncpy(dest2, source, 7);
printf("%s\n", dest2);

strcpy(dest1, source);
printf("%s\n", dest1);
return 0;
}

 The above code prints the following outputs:

  • New to
  • New to C programming

...