type-qualifiers
正如标题中提到的,如果影响声明符的存储位置(stack
等) ,我有点困惑bss
。为了描述更多,我正在考虑以下声明。
int main()
{
const int value=5;
const char *str= "Constant String";
}
- 在上面的代码中,默认
storage-class-specifier
是auto
. - 因此,假设这些常量将在创建时
stack-frame
分配。main
- 通常,
pointers
堆栈中的各个内存位置都可以自由修改其中包含的值。 - 因此,从以上几点可以理解,要么
type-qualifier
添加一些逻辑来保留所constant
存储元素的性质(如果是这样,它是什么?),要么constants
存储在read-only-portion
内存中。请详细说明这一点。
更详细的例子
#include <stdio.h>
int main(void)
{
int val=5;
int *ptr=&val;
const int *cptr=ptr;
*ptr=10; //Allowed
//*cptr=10; Not allowed
//Both ptr and cptr are pointing to same locations. But why the following error?
//"assignment of read-only location ‘*cptr’"
printf("ptr: %08X\n",ptr);
printf("cptr: %08X\n",cptr);
printf("Value: %d\n",*ptr);
}
在上面的例子中,两者都cptr
指向ptr
同一个位置。但是cptr
是指向const type qualified
整数的指针。在修改 的值时cptr
,编译器会抛出一个错误为"assignment of read-only location '*cptr'"。但我可以使用 修改相同的位置,ptr
如下面的输出所示。请解释
ptr: BFF912D8
cptr: BFF912D8
Value: 10