const int*ptr = 500;它存储的确切位置

sra*_*thi 1 c linux const

我知道,const int *ptr我们可以更改地址但不能更改值.即,ptr将存储在读写部分(堆栈)中,并且对象或实体将存储在数据分段的只读部分中.因此,我们可以更改指针指向的地址ptr,但不能更改常量对象.

int main()
{
  const int *ptr=500;
  (*ptr)++;
  printf("%d\n",*ptr);
}
Run Code Online (Sandbox Code Playgroud)

output是将只读位置分配给*ptr

int main()
{
  const int *ptr=500;
  ptr++;
  printf("%d\n",*ptr);
}
Run Code Online (Sandbox Code Playgroud)

没有编译错误,但在运行时输出是"分段错误".

我同意第一个问题,为什么我在第二个中遇到分段错误?它们究竟存放在哪里?

438*_*427 5

分段错误的原因与您的想法不同.

不是因为const.

这是因为您不允许访问您尝试访问的区域 *ptr

当您指向"某事物"时,仍然不允许您访问数据(也就是取消引用指针),直到您将指针指向属于您的某些内存为止.

例:

int x = 0;
int* p = (int*)500;

int a = *p;  // Invalid - p is not pointing to any memory that belongs to the program

p = &x;
int b = *p;  // Fine - p is pointing to the variable x

p++;
int c = *p;  // Invalid - p is not pointing to any memory that belongs to the program
Run Code Online (Sandbox Code Playgroud)

"无效"代码可能会产生分段错误.另一方面,它也可能只是执行并产生意外结果(甚至更糟:产生预期结果).