copying a string - simple question!

This is a discussion on copying a string - simple question! within the C Programming forums, part of the General Programming Boards category; Hi, I have a string char *input and i just want to make a copy of it - char *inputcopy ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,437
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Apr 2011
    Location
    dust
    Posts
    63
    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,200
    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%.

  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, 10:36 AM
  5. simple string question
    By c_cool in forum C Programming
    Replies: 4
    Last Post: 07-30-2004, 12:27 PM

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