Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy of a string pointer

Tags:

c

string

pointers

I have a function that has input and pointer to an array of char in C. in that function I am manipulating the main string, however I want to make a backup copy in another variable before I use it. I want to put it in char backup[2000], so if the pointer changes the backup won't change. How can I do that?

like image 716
Syntax_Error Avatar asked Mar 23 '11 16:03

Syntax_Error


1 Answers

void function (const char *string)
{
   char *stringcopy = malloc (1 + strlen (string));
   if (stringcopy)
       strcpy (stringcopy, string);
   else  fprintf (stderr, "malloc failure!"):
   ...
   do whatever needs to be done with `stringcopy`
}
like image 153
wallyk Avatar answered Jan 19 '23 14:01

wallyk