As explained by Philip Potter, the main difference is that memcpy will copy all n characters you ask for, while strncpy will copy up to the first null terminator inclusive, or n characters, whichever is less. In the event that strncpy copies less than N characters, it will pad the rest out with null characters.
The below program will answer your question:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char s[10] = "qwerty",str1[10];
int i;
s[7] = 'A';
memcpy(str1, s, 8);
for(i=0;i<8;i++)
{
if(str1[i]!='\0')
printf("%c",str1[i]);
}
return 0;
}
o/p:
qwertyA
Execute the below code and check the difference, you might find it useful.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char s[10] = "qwer\0ty", str[10], str1[10];
s[7] = 'A';
printf("%s\n",s);
strncpy(str,s,8);
printf("%s\n",str);
memcpy(str1,s,8);
printf("%s\n",str1);
for(int i = 0; i<8; i++)
{
printf("%d=%c,",i,str[i]);
}
printf("\n");
for(int i = 0; i<8; i++)
{
printf("%d=%c,",i,str1[i]);
}
return 0;
}
Output:
qwer
qwer
qwer
0=q,1=w,2=e,3=r,4=,5=,6=,7=,
0=q,1=w,2=e,3=r,4=,5=t,6=y,7=A,
memcpy
andstrncpy
in your above code. Then experience the difference. – Queensland