Thread: Copy a string

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    115

    Copy a string

    Hello

    I am trying to copy a string that doesn't have a fixed size.
    What is the way to do it?


    char *search, *split;
    ......
    search = split; doesn't work

    strcpy(search, split); doesn't work
    Thank you

  2. #2
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    Looks like the so-called string isn't null terminated otherwise strcpy() would have worked.
    Post more details about the string as it is not easy to figure out what you are getting at.

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    115
    Well, I am trying to copy the string from buff to search.
    I get a seg fault at the strcpy line.

    I want to adapt the "search" string and leave the "buf" string intact
    Code:
    	
    
            char *search, *buf;
    	
    	buf = ("Hello");
    	search = NULL;
    
    	printf("buf: %s\n", buf);
    	strcpy(search, buf);
    	
    	printf("search: %st\n", search);
    	strcat(search, " ");
    	printf("buf: %st\n", buf);
    	printf("search: %st\n", search);

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    74
    You have to allocate memory first before copying into search.

  5. #5
    Registered User
    Join Date
    Feb 2010
    Posts
    115
    Thank you !!

  6. #6
    Password:
    Join Date
    Dec 2009
    Location
    NC
    Posts
    587
    Code:
    char *search, *split;
    ......
    strcpy((search = malloc((strlen(split) + 1) * sizeof(char))), split);
    sizeof(char) is for clarity, the compiler will(or should) ignore it since it evals to a constant 1.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Polymorphism and generic lists
    By Shibby3 in forum C# Programming
    Replies: 9
    Last Post: 07-26-2010, 05:27 AM
  2. Help for my assigment
    By cloverdagreat in forum C Programming
    Replies: 16
    Last Post: 11-21-2009, 12:18 PM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  4. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  5. Replies: 3
    Last Post: 11-03-2002, 02:14 AM