是否有一个函数可以将字符串复制到内存中的新空间

问题描述 投票:0回答:1

如果我想在C编程中将字符串“Best School”复制到内存中的新空间中,我可以使用什么语句为其保留足够的空间

我尝试过使用这个

malloc(strlen("Best School") + 1)

还有这个

malloc(sizeof("Best School"))

c malloc heap-memory free calloc
1个回答
0
投票

分配内存块并将空终止字符串复制到其中的最简单、最安全的方法是:

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.