我们必须假设a 是NUL 终止的(以'\0' 结尾),否则我们无法确定它的大小/长度(除非您自己知道a 的长度)。
char *a = "Hello World"; /* say for example */
size_t len = strlen(a)+1; /* get the length of a (+1 for terminating NUL ('\0') character) */
请注意,如果您知道a 指向(或保存在)中的字符串的长度,那么您将把它分配给len,而不是使用上面的语句。
char *b = calloc(1, len); /* */
memcpy(b, a, len); /* now b contains copy of a */
如果您的意图只是复制一个字符串(NUL 终止),您可以使用strdup()(在string.h 中声明):
char *b = strdup(a); /* b now has a copy of a */
注意:strdup() 在 POSIX 中。如果你想要严格的 ANSI C,那么你可以像我之前提到的那样制作一个包装器:
unsigned char *my_strdup(const unsigned char *a)
{
size_t len = strlen(a)+1;
unsigned char *b = calloc(1, len);
if (b) return (unsigned char *) memcpy(b, a, len);
return NULL; /* if calloc fails */
}