Thread: copying a string - simple question!

  1. #1
    Registered User
    Join Date
    Dec 2011
    Posts
    7

    copying a string - simple question!

    Hi,

    I have a string char *input and i just want to make a copy of it - char *inputcopy

    if i say inputcopy = input and then change input then inputcopy changes too which I don't want. If i use strcpy(inputcopy, input) then I get a segmentation fault. I'd appreciate any help, it's driving me crazy!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Well you need to call malloc() to allocate some space for your copy, then use strcpy() to make a copy.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Apr 2011
    Location
    dust
    Posts
    70
    inputcopy = input /*Both the pointers will point to same memory where the actual string stored*/

    if you are going to use strcpy, first allocate enough memory for inputcopy pointer then do strcpy

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    A pointer to char is not a string.

    You need to use strcpy(), but also ensure inputcopy is associated with an array large enough to accept the contents of input.

    For example;
    Code:
          char inputcopy[some_length];    // some_length must be at least strlen(input)+1
          strcpy(inputcopy, input);
    or
    Code:
        char *inputcopy = malloc(strlen(input) + 1);
        strcpy(inputcopy, input);
        free(inputcopy);
    or (if your compiler is C99 compliant only)
    Code:
        char inputcopy[strlen(input) + 1];
        strcpy(inputcopy, input);
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  5. #5
    Registered User
    Join Date
    Dec 2011
    Posts
    7
    thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. very simple string question
    By camel-man in forum C Programming
    Replies: 5
    Last Post: 05-10-2011, 07:43 PM
  2. Simple string question
    By gareth00 in forum C Programming
    Replies: 12
    Last Post: 10-27-2008, 11:19 AM
  3. string simple question
    By -EquinoX- in forum C Programming
    Replies: 1
    Last Post: 04-12-2008, 01:28 PM
  4. Replies: 1
    Last Post: 10-31-2005, 11:36 AM
  5. simple string question
    By c_cool in forum C Programming
    Replies: 4
    Last Post: 07-30-2004, 12:27 PM