您可以strdup()
用来返回 C 字符串的副本,如下所示:
#include <string.h>
const char *stringA = "foo";
char *stringB = NULL;
stringB = strdup(stringA);
/* ... */
free(stringB);
您也可以使用strcpy()
,但您需要先分配空间,这并不难,但如果没有正确完成,可能会导致溢出错误:
#include <string.h>
const char *stringA = "foo";
char *stringB = NULL;
/* you must add one to cover the byte needed for the terminating null character */
stringB = (char *) malloc( strlen(stringA) + 1 );
strcpy( stringB, stringA );
/* ... */
free(stringB);
如果您不能使用strdup()
,我建议使用 ofstrncpy()
而不是strcpy()
。该strncpy()
函数最多复制 - 并且最多复制 -n
字节,这有助于避免溢出错误。但是,如果strlen(stringA) + 1 > n
您需要stringB
自己终止 ,。但是,一般来说,你会知道你需要什么尺寸的东西:
#include <string.h>
const char *stringA = "foo";
char *stringB = NULL;
/* you must add one to cover the byte needed for the terminating null character */
stringB = (char *) malloc( strlen(stringA) + 1 );
strncpy( stringB, stringA, strlen(stringA) + 1 );
/* ... */
free(stringB);
我自己认为strdup()
更干净,所以我尝试在专门处理字符串的情况下使用它。我不知道 POSIX/非 POSIX 方法在性能方面是否有严重的缺点,但我不是 C 或 C++ 专家。
请注意,我将结果转换为malloc()
to char *
。这是因为您的问题被标记为c++
问题。在 C++ 中,需要将结果从malloc()
. 但是,在 C 中,您不会强制转换它。
编辑
你去吧,有一个复杂性:strdup()
不在 C 或 C++ 中。因此,使用strcpy()
orstrncp()
与预先确定大小的数组或malloc
-ed 指针一起使用。在您可能使用该功能的任何地方,使用strncp()
代替 是一个好习惯。strcpy()
这将有助于减少出错的可能性。