我最近了解到,可以使用指针更改 c 中的常量值,但对于字符串文字却不可能。可能的解释在于常量和其他字符串在空间中的可修改区域中分配空间,而字符串文字在空间中的不可修改区域(可能是代码段)中分配空间。我编写了一个程序来显示这些变量的地址。输出也显示出来。
#include <stdio.h>
int x=0;
int y=0;
int main(int argc, char *argv[])
{
const int a =5;
const int b;
const int c =10;
const char *string = "simar"; //its a literal, gets space in code segment
char *string2 = "hello";
char string3[] = "bye"; // its array, so gets space in data segment
const char string4[] = "guess";
const int *pt;
int *pt2;
printf("\nx:%u\ny:%u Note that values are increasing\na:%u\nb:%u\nc:%u Note that values are dec, so they are on stack\nstring:%u\nstring2:%u Note that address range is different so they are in code segment\nstring3:%u Note it seems on stack as well\nstring4:%u\n",&x,&y,&a,&b,&c,string,string2,string3,string4);
}
请解释这些变量究竟在哪里获得空间?全局变量从哪里获得空间,常量从哪里获得,字符串文字从哪里获得?