strncpy() & memcpy() function in C

What is the difference between strncpy()(not strcpy) & memcpy() function in C?

Questions by Muthupandi_s

Showing Answers 1 - 9 of 9 Answers

strcpy is meant to copy only null-terminated strings. It is probably
: implemented to copy every byte until it encounters a #0.
: memcpy can copy any memory location. It is not bound by a
: null-terminated string. Since memcpy cannot determine the size of
: the data to be copied, it needs the programmer to provide that
: information.


That is correct. Note that there is also a function called strncpy() which copies n bytes. It is almost identical to memcpy(), with the difference that it adds null termination at the end of the target string.

jca_dips

  • Jul 18th, 2008
 

strncpy copies upto null or specified no. of bytes, whichever is less. But memcpy overlooks null, and copies all specified no. of bytes. 
None of them adds null in destination string by itself. 

#include<conio.h>
#include<memory.h>
#include<string.h>

void main()
{
 char str1[50] = "This is india: a wonderful country";
    char str2[30];
 
 printf("%s",str1);
 strncpy(str2,str1,15);
 //memcpy(str2,str1,15);
 //str2[12] = '';
 printf("n%s",str2);
 printf("n%c%c",str2[12],str2[13]);

 getch();



str1[8] is null. As strncpy copies upto null, str[12] and str[13] takes value as blank.
In case of memcpy as all the specifed 15 bytes are copied in the destination string,
str[12] takes 'i' and str[13] takes 'a' as values. 

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions