No of visitors who read this post: 280
Category: Storage Misc
Type: Question
Author: Mart cullen
No votes yet

What is the difference between a string copy (strcpy) and a memory copy (memcpy)?When should be the best time to use one over the other?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

#

strcpy  (string copy) copies all the information associated with a certain variable of string.  memcpy (memory copy) copies a block of information specified in the last argument of the function.

Following is the code for MEMCPY

#include <stdio.h>

#include <string.h>

#include <iostream.h>

void main ()

{

  char str1[]="Sample text to copy";

  char str2[40];

  char str3[40];

  memcpy (str2, str1, strlen(str1)+1);

  memcpy (str3,"copying done",13);

  cout<< "str1: " <<str1<< “ \nstr2: ” <<str2<< “\nstr3: ”<< str3;

}

the output is the picture attached..

Sample output_memcpy

-----------strcpy on the other hand provides the same output but just removing the last argument in memcpy...

strcpy (str1, str2) --> given that str1 is destination of the copied text and str2 is the source of text...

you can use whatever code you find it easy with and makes you more comfortable..