C语言 字符串指针的副本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5408871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
copy of a string pointer
提问by Syntax_Error
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?
我有一个函数,它具有输入和指向 C 中字符数组的指针。在该函数中,我正在操作主字符串,但是我想在使用它之前在另一个变量中制作一个备份副本。我想把它放在 char backup[2000] 中,所以如果指针改变,备份不会改变。我怎样才能做到这一点?
回答by wallyk
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`
}
回答by jdehaan
To duplicate strings in C there is a library function called strdupmade for that:
要在 C 中复制字符串,有一个为此调用的库函数strdup:
The memory allocated by strdupmust be freed after usage using free.
分配的内存strdup必须在使用后释放free。
strdupprovides 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.
strdup一步提供内存分配和字符串复制操作。如果在某个时间点要复制的字符串恰好大于数组的大小,则使用字符数组可能会出现问题。
回答by jibril
Your friends are the following functions
你的好友有以下功能
- malloc
- memset
- calloc
- memcpy
- strcpy
- strdup
- strncpy
- malloc
- 内存集
- 钙质
- 内存
- 链表
- 串连
- 强度
But best of all, greatest friend is man:)
但最重要的是,最好的朋友是人:)
回答by Andy Johnson
Use strncpy().
使用 strncpy()。
void myfunc(char* inputstr)
{
char backup[2000];
strncpy(backup, inputstr, 1999);
backup[1999] = 'char backup[2000];
char original[2000];
sprintf(original, "lovely data here");
memcpy(backup, original, 2000);
char* orig_ptr = original;
';
}
Copying 1999 characters to the 2000 character array leaves the last character for the null terminator.
将 1999 个字符复制到 2000 个字符数组会留下最后一个字符作为空终止符。
回答by eat_a_lemon
Use memcpy to create the backup.
使用 memcpy 创建备份。
strcpy( backup, source );
回答by Mahesh
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.
为避免溢出,destination 指向的数组的大小应足够长以包含与 source 相同的 C 字符串(包括终止空字符),并且不应与 source 在内存中重叠。

