考虑以下代码:
#include<stdio.h>
int main()
{
const char* c = malloc(1);
*c = 'a';
printf("%c\n",*c);
}
Run Code Online (Sandbox Code Playgroud)
该代码显然会引发以下编译错误:
file1.c:7:3: error: assignment of read-only location ‘*c’
*c = 'a';
^
Run Code Online (Sandbox Code Playgroud)
如何在堆内存中初始化const变量?
首先,要了解没有“只读堆中的位置”之类的东西。堆是100%可写的。 malloc()被定义为returning void *。您可以写入malloc返回的指针所指向的数据。
但是接下来要了解的第二件事是,const它也不一定意味着“只读”。
还有就是这样的事,作为只读存储器,它会经常被指出const的指针,如果(尽管任何const指针)你设法尝试写入只读存储器,你通常会得到某种异常。
但是,您可以拥有由非const指针const指向的只读内存,并且可以具有指向可写内存的指针。
因此,const真正的意思是“我保证不写该存储器”或“我声明不写该存储器”,并增加了以下规定:“如果不小心,我希望编译器给我编译时错误。尝试写入此内存。”
如果有普通const指针,则可以将其初始化一次。你可以说像
const str1[] = "hello";
Run Code Online (Sandbox Code Playgroud)
和
const *str2 = "world";
Run Code Online (Sandbox Code Playgroud)
即使以后尝试更新类似的字符串
*str1 = 'x'; /* WRONG */
Run Code Online (Sandbox Code Playgroud)
要么
*str2 = 'y'; /* WRONG */
Run Code Online (Sandbox Code Playgroud)
会失败。(您可以将其视为const合格数据的“初始化例外” 。
但是,正如您所发现的那样,const通过调用初始化的指针没有这种例外malloc。如果您想从中获取一些内存malloc,并对其进行一次初始化,然后保证以后不再修改它,并且如果您想让编译器为您强制执行此承诺,则不能直接执行,除非您使用评论和klutt的答案中所述的两点解决方法。
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |