让一个char *的副本 [英] Make a copy of a char*
问题描述
我有一个接受一个char *作为它的一个参数的函数。我需要对其进行操作,但保留原始的char *完好无损。从本质上讲,我想创建此CHAR的工作副本*。看起来这应该很容易,但我真的很挣扎。
I have a function that accepts a char* as one of its parameters. I need to manipulate it, but leave the original char* intact. Essentially, I want to create a working copy of this char*. It seems like this should be easy, but I am really struggling.
我的第一个(天真)的尝试是创建另一个字符*,并设置它等于原来的:
My first (naive) attempt was to create another char* and set it equal to the original:
char* linkCopy = link;
这是不行的,当然,因为我所做的就是使他们指向同一个地方。
This doesn't work, of course, because all I did was cause them to point to the same place.
我应该用函数strncpy做到这一点?
Should I use strncpy to accomplish this?
我曾尝试以下,但它会导致崩溃:
I have tried the following, but it causes a crash:
char linkCopy[sizeof(link)] = strncpy(linkCopy, link, sizeof(link));
我失去了一些东西明显...?
Am I missing something obvious...?
编辑:我的道歉,我正在努力简化的例子,但我留下了一些在第二个例子中长变量名。固定的。
My apologies, I was trying to simplify the examples, but I left some of the longer variable names in the second example. Fixed.
推荐答案
的的sizeof
会给你指针的大小。这往往是4或8取决于你处理器/编译器,但不包括字符串的大小指出。您可以使用strlen和strcpy:
The sizeof
will give you the size of the pointer. Which is often 4 or 8 depending on your processor/compiler, but not the size of the string pointed to. You can use strlen and strcpy:
// +1 because of '\0' at the end
char * copy = malloc(strlen(original) + 1);
strcpy(copy, original);
...
free(copy); // at the end, free it again.
我见过一些答案建议使用的strdup
,但是这是一个POSIX函数,而不是C的一部分。
I've seen some answers propose use of strdup
, but that's a posix function, and not part of C.
这篇关于让一个char *的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!