c - Make a copy of a char* -


I have functions that accept four parameters as one of their criteria. I need to manipulate this, but leave the original letter * intact. Basically, I want to make a working copy of this four *. It seems that it should be easy, but I'm really struggling.

My first (inexperienced) attempt was to make one and four * and set it equal to the original:

  four * linkcopy = link;  

This does not work, of course, because I had delivered them all to one place.

Should I use strncpy to accomplish this? / P>

I have tried the following, but it causes an accident:

  copy of four links [sizeof (link)] = strncpy (linkCopy, link, sizeof (Link);  

Am I missing something clear ...?

EDIT: My apologies, I was trying to simplify the examples, but I left the names of some variables, the second example is fixed.

sizeof will give you the size of the indicator. Which is often 4 or 8 based on your processor / compiler, but does not point to the string size. You can use strlen and strcpy:

  // +1 end in '\ 0' due to * copy = malloc (strlen (original) + 1); Strapepy (copy, original); ... Free (duplicate); // Finally, free it again  

I have proposed using some of the answers to strdup , but this is a Pausx function, and C Not a part.


Comments