无法自由使用C常量指针 [英] Unable to free const pointers in C
本文介绍了无法自由使用C常量指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎么能释放一个为const char *
?我使用的malloc
分配新的内存,当我试图释放它,我总是收到错误不兼容的指针类型
在code导致此是一样的东西:
的char * name =阿诺德;
为const char *海峡=(为const char *)malloc的(strlen的(名字)+1);免费(STR); //此处错误
解决方案
有几个人已经张贴了正确的答案,但他们保持删除它由于某种原因。您需要将其转换为一个非const指针; 免费
需要无效*
,而不是常量无效*
免费((字符*)STR);
How can I free a const char*
? I allocated new memory using malloc
, and when I'm trying to free it I always receive the error "incompatible pointer type"
The code that causes this is something like:
char* name="Arnold";
const char* str=(const char*)malloc(strlen(name)+1);
free(str); // error here
解决方案
Several people have posted the right answer, but they keep deleting it for some reason. You need to cast it to a non-const pointer; free
takes a void*
, not a const void*
:
free((char*)str);
这篇关于无法自由使用C常量指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文