Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 为什么内存地址在一个地方上升,在另一个地方下降?_C_Arrays - Fatal编程技术网

C 为什么内存地址在一个地方上升,在另一个地方下降?

C 为什么内存地址在一个地方上升,在另一个地方下降?,c,arrays,C,Arrays,下面是我编写的一个简单的C程序: int main(void) { char str[]="abcde"; int len = strlen(str); for(int i=0;i<len;i++) printf("%c : %p\n",str[i], (void*) &str[i]); int a,b,c,d,e=10; printf("The memory address of a is: %p\n", (void*) &a); printf("The me

下面是我编写的一个简单的C程序:

int main(void) {
char str[]="abcde";
int len = strlen(str);
for(int i=0;i<len;i++)
    printf("%c : %p\n",str[i], (void*) &str[i]);

int a,b,c,d,e=10;

printf("The memory address of a is: %p\n", (void*) &a);
printf("The memory address of b is: %p\n", (void*) &b);
printf("The memory address of c is: %p\n", (void*) &c);
printf("The memory address of d is: %p\n", (void*) &d);
printf("The memory address of e is: %p\n", (void*) &e);
    return 0;
}

为什么
char
数组的内存地址增加而
int
s的内存地址减少?

这是编译器和体系结构的细节,a-e的顺序是什么。这些变量位于堆栈上,在大多数(但不是所有)体系结构上,堆栈向下增长——也就是说,最内层的函数将具有具有最低地址的局部变量,而调用该函数的函数将具有具有较高地址的局部变量。在这样的情况下(所有变量都在同一个函数中声明,特别是在同一个作用域中),编译器可以选择将什么放在哪里,而且看起来您的编译器已经选择按声明的顺序将它们向下排序


相反,在数组中,元素的内存位置几乎保证按索引的升序排列。(IIRC,从技术上讲,这是不允许的,但我不知道有哪个编译器是虐待狂。)

这完全取决于实现。在这种情况下,数组向上增长,堆栈向下增长。我猜如果你打开优化,事情的可预测性会大大降低。
a : 0x7fff59e358a6
b : 0x7fff59e358a7
c : 0x7fff59e358a8
d : 0x7fff59e358a9
e : 0x7fff59e358aa
The memory address of a is: 0x7fff59e35898
The memory address of b is: 0x7fff59e35894
The memory address of c is: 0x7fff59e35890
The memory address of d is: 0x7fff59e3588c
The memory address of e is: 0x7fff59e35888