String copy

This is a discussion on String copy within the C Programming forums, part of the General Programming Boards category; Hi, Is it ok to make a copy of my string like this? char *s1 = malloc(sizeof(char)*6); char *s2 = ...

  1. #1
    Waxy-Dock
    Join Date
    Mar 2005
    Posts
    69

    String copy

    Hi,

    Is it ok to make a copy of my string like this?

    char *s1 = malloc(sizeof(char)*6);
    char *s2 = malloc(sizeof(char)*6);

    /* do some processing on s1 */

    s2 = s1;

    or do i need to use that string copy function?

  2. #2
    Registered Abuser
    Join Date
    Jun 2006
    Location
    Toronto
    Posts
    591
    No, you need to use either strcpy or memset (or even a simple while loop).
    What the above does just allocates 6 bytes and then lets it leak, as well, no copying takes place other than address location values.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    s1 is a pointer, s2 is a pointer.

    If you assign the value of one pointer to another pointer, you've just changed the value of a pointer, not done anything with an array of char's.

    In C, why not use strcpy(), to copy a string?

    This function, strcpy() should *leap* right out at you as something to use perhaps, to copy a string, automatically; just in a moment ==> strcpy() to copy strings.

    I have tried to use strcpy to race homing pigeons, fix engines and tires, and provide marital counseling --> didn't work! Use it to copy strings; it's all it's good for!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 04:45 PM
  2. Replies: 4
    Last Post: 03-03-2006, 01:11 AM
  3. problems with overloaded '+' again
    By Brain Cell in forum C++ Programming
    Replies: 9
    Last Post: 04-14-2005, 05:13 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 01:45 PM
  5. Replies: 3
    Last Post: 11-03-2002, 01:14 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21