C中的全局变量地址

时间:2020-04-10 09:04:02

标签: c global-variables

我试图找出全局变量的C内存布局。 这是我使用的程序:

#include <stdio.h>
int a = 1;
char *b = "moish";
//char b[6] = {'m','o','i','s','h',0};
int c = 3;
int d = 4;
int e = 5;

int main(int argc, char **argv)
{
    printf("location: %p\n",&a);
    printf("location: %p\n", b);
    printf("location: %p\n",&c);
    printf("location: %p\n",&d);
    printf("location: %p\n",&e);
    return 0;
}

当我编译并运行它时,假设合理对齐,我得到了我期望的结果 其中变量c位于0x56294fab001c而不是0x56294fab001a等处。

location: 0x56294fab0010
location: 0x56294fab0014
location: 0x56294fab001c
location: 0x56294fab0020
location: 0x56294fab0024

使用char *b = "moish"时,我得到一个完全不同的地址:

location: 0x55c676551010
location: 0x55c676350784
location: 0x55c676551014
location: 0x55c676551018
location: 0x55c67655101c

那是为什么?我以为这两个选项是等效的,不是吗?

2 个答案:

答案 0 :(得分:1)

这是一个实际的数组

char b[6] = {'m','o','i','s','h',0}; // size is 6 byte

这只是一个指针,它指向只读存储器位置,因为它是一个常量字符串,所以被放置在“ moish”位置。

char *b = "moish"; // size is the char pointer size of the architecture

实际上,这实际上是char b[6] = {'m','o','i','s','h',0};

的等效项
char b[] = "moshi"; // or char b[6] = "moshi" , does not matter in this case

答案 1 :(得分:0)

声明时

int a;
char b[6];
int c;

变量b占据a和c之间的空间,这是您所期望的。当您声明

int a;
char* b;
int c;

并打印a,b和c的地址,您将获得与打印b预期的连续地址:而不是&b。打印出b指向的内容:而不是b的地址。它正在打印“ moish”的位置,该位置可能在完全不同的区域。

修改 只需将其视为RAM和ROM。可以更改的是RAM,不能更改的是ROM。如果您声明

int a;
const char* b = "moish";
const char c[] = "hsiom";
int d;

a,b和d将在RAM中,c和“ moish”将在ROM中。打印&a,&b和&d将得到RAM地址。打印b和c将得到ROM地址。由于b是变量,因此可以

b = c;

但不是

c = b;
相关问题