Memcpy vs. =

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mjbauer95
    New Member
    • Jan 2009
    • 13

    Memcpy vs. =

    What is the difference between memcpy() and just using the = symbol, as in:
    Code:
    char * str1;
    str1 = "TEST.";
    char * str2;
    str2 = str1;
    vs.

    Code:
    char * str1;
    str1 = "TEST.";
    char * str2;
    strcpy(str2,str1);
    What are the advantages of using strcpy because that seems to be the "right" way?
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    Code:
    char * str1; //str1 is a pointer of type char
    str1 = "TEST."; //str1 is assigned "TEST" or is initialised to "TEST"
    char * str2; //str2 is a pointer of type char
    str2 = str1; str2 is assigned str1
    vs.
    
    Expand|Select|Wrap|Line Numbers
     char * str1; //same as above
    str1 = "TEST."; //same as above
    char * str2; //same as above
    strcpy(str2,str1);//copy str1 into str2
    memcpy() copies whats in memory at a specified location to another specified location in memory.

    Comment

    • santoshmp
      New Member
      • Feb 2009
      • 2

      #3
      str2 = str1 simply assigns whatever address is there in str1 to str2.

      memcpy and strcpy is almost the same in that it copies the contents of the memory pointed to by str2 to memory pointed to by str1. For memcpy you specify the number of bytes to be copied. strcpy on the other hand will copy all the contents till it finds a NULL character.

      In you example, using strcpy or memcpy is not correct because str2 does not point to any memory allocation. It is pointing to some random location and so will cause a crash.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Originally posted by santoshmp
        str2 = str1 simply assigns whatever address is there in str1 to str2.
        Which means that str1 and str2 point to the same memory locations.
        Code:
            str2[0] = 'T';
            str1[0] = 'A';
            if (str2[0] == 'T')
                ...
            else
                ...
        The else-branch will be taken.

        Comment

        Working...