开发者

copy of a string pointer

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 chang开发者_开发问答e. How can I do that?


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`
}


To duplicate strings in C there is a library function called strdup made for that:

The memory allocated by strdup must be freed after usage using free.

strdup provides the memory allocation and string copy operation in one step. Using an char array can become problematic if at some point in time the string to copy happens to be larger than the array's size.


Your friends are the following functions

  • malloc
  • memset
  • calloc
  • memcpy
  • strcpy
  • strdup
  • strncpy

But best of all, greatest friend is man :)


Use strncpy().

void myfunc(char* inputstr)
{
    char backup[2000];
    strncpy(backup, inputstr, 1999);
    backup[1999] = '\0';
}

Copying 1999 characters to the 2000 character array leaves the last character for the null terminator.


You can use strcpy to make a copy of your char array (string) before you start modifying.


Use memcpy to create the backup.

char backup[2000];
char original[2000];

sprintf(original, "lovely data here");
memcpy(backup, original, 2000);

char* orig_ptr = original;


strcpy reference.

strcpy( backup, source );

Note from link.

To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜