如果我想在C编程中将字符串“Best School”复制到内存中的新空间中,我可以使用什么语句为其保留足够的空间
我尝试过使用这个
malloc(strlen("Best School") + 1)
还有这个
malloc(sizeof("Best School"))
分配内存块并将空终止字符串复制到其中的最简单、最安全的方法是:
char *ptr = strdup(“Best School”);
strdup()
在 <string.h>
中声明,自 C23 和 POSIX 诞生以来,它是 C 标准的一部分。它在大多数系统上都可用,并且可以这样定义:
#include <stdlib.h>
char *strdup(const char *s) {
size_t size = strlen(s) + 1;
char *p = malloc(size);
return p ? memcpy(p, s, size) : NULL;
}