关于C中可变内存地址的观察

Smo*_*otQ 2 c memory-address

我有一个问题而不是一个问题(巫婆可能会出现一个记忆问题)..我写了这个简单的程序:

#include <stdio.h>
#include <stdlib.h>

int multi(int x, int y);


int main(){
    int x;
    int y;
    printf("Enter the first number x: \n");
    scanf("%d",&x);
    printf("Enter the second number y: \n");
    scanf("%d",&y);
    int z=multi(x,y);
    printf("The Result of the multiplication is : %d\n",z,"\n");
    printf("The Memory adresse of x is : %d\n",&x);
    printf("The Memory adresse of y is : %d\n",&y);
    printf("The Memory adresse of z is : %d\n",&z);
    getchar();
    return 0;
}

int multi(int x,int y){
    int c=x*y;
    printf("The Memory adresse of c is : %d\n",&c);
    return c;  
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的(如果您使用C开发),此程序输入2个int变量,然后将它们与多功能相乘:

得到的结果之后,它显示在存储器中的每个变量的位置(c,x,yz).

我已经测试了这个简单的例子,结果是这些(在我的例子中):

The Memory adresse of c is : 2293556  
The Result of the multiplication is : 12  
The Memory adresse of x is : 2293620  
The Memory adresse of y is : 2293616  
The Memory adresse of z is : 2293612  
Run Code Online (Sandbox Code Playgroud)

你可以看到,这三个变量x,y,z即在主函数中声明已经关闭内存不会忽略(22936xx),c.该变量在多函数声明有不同的ADRESS(22935xx).

x,yz变量,我们可以看到,有两两个变量之间的4个字节的差(即:&x-&y=4,&y-&z=4).

我的问题是,为什么每两个变量之间的差异等于4?

Emi*_*Sit 5

x,yz,是将在调用堆栈上创建的整数变量(但见下文).这sizeof int是4个字节,因此编译器将在堆栈上为这些变量分配多少空间.这些变量彼此相邻,因此它们相隔4个字节.

您可以通过查找有关调用约定的信息来了解如何为局部变量分配内存.

在某些情况下(您不使用address-of运算符),编译器可能会将局部变量优化为寄存器.