请考虑以下代码。我问这是否正确,是否缺少某些内容。有没有其他方法可以做到。
#include <stdio.h>
#include <string.h>
const char *getOrder (const char *day)
{
if (strncmp(day, "Monday", 7) == 0) {
return "first";
} else if (strncmp(day, "Tuesday", 7) == 0) {
return "second";
} else if (strncmp(day, "Wednesday", 9) == 0) {
return "third";
} else if (strncmp(day, "Thursday", 8) == 0) {
return "forth";
} else if (strncmp(day, "Friday", 6) == 0) {
return "fifth";
} else if (strncmp(day, "Saturday", 8) == 0) {
return "sixth";
} else if (strncmp(day, "Sunday", 6) == 0) {
return "seventh";
} else
return NULL;
}
int main()
{
const char* str = NULL;
str = getOrder ("Monday");
printf("str : %s\n", str);
return 0;
}
最佳答案
决定是否必须释放的不是变量的类型,而是它驻留在内存的哪一部分。
如果您使用 malloc
分配内存或相关功能,它将存在于 heap 上,因此您必须调用 free
在他们身上。
在您的示例中,这些字符串是在 static memory 中创建的(不是像其中一条评论中建议的那样来自堆栈,否则函数返回后您将无法使用它,因为它们会被覆盖)。
这些字符串被编译成运行时二进制文件本身(你可以运行 strings <your binary>
你会看到它们。一旦程序被加载,内存的一个特殊区域被保留用于这些常量数据,因此你不需要不需要释放它。
作为旁注,您必须从右到左阅读 C/C++ 类型,所以
输入 const char*
意思是你有一个指向常量字符串的指针。这意味着你不能修改它指向的字符串,但它并没有说明这个指针后面的内存是如何分配的。它可能在堆上,在 stack 上,或者在静态内存上,只是类型不会告诉你。
关于c - const char* 应该在 C 中释放吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73124321/