如果在循环内声明了指针变量,则循环的每个遍历都将其与相同的内存地址相关联吗? [英] if a pointer variable is declared inside a loop, is it associated with the same memory address each pass of the loop?

查看:74
本文介绍了如果在循环内声明了指针变量,则循环的每个遍历都将其与相同的内存地址相关联吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有变量,则存在与该变量关联的内存地址,对于指针变量,该内存地址的值"是对保存实际数据的内存地址的引用.指针指向.

If you have a variable, there is a memory address associated with that variable, and in the case of a pointer variable, the "value" of that memory address is a reference to the memory address that holds the actual data that the pointer points to.

所以,如果我有:

for (int x = 0; x < 2; x++)
{
    char * a = (char*)malloc(20);
    printf("%p\r\n", &a);
    printf("%p\r\n", a);
}

输出应类似于:

    00999999
    04427310
    00999999
    0442ECF0

正如您所看到的,在每次循环过程中声明的指针变量的第一个和第三个内存地址都保持不变,我的理解是因为上一个变量超出了范围,而下一个超出了范围可用地址是相同的地址.

And as you can see, the 1st and the 3rd memory address remain the same for the pointer variables declared during each pass of the loop, and my understanding is that this is so because the previous variable went out of scope and the next available address is the same address.

可以将此泛化扩展到循环内声明的所有变量,还是有例外?

Can this generalization be extended to all variables declared inside a loop or are there exceptions?

推荐答案

通常是堆栈的工作方式.而且这与变量类型无关.当堆栈向下生长时,它可能看起来或多或少像这样

That's how a stack usually works. And this is independent of variable type. When the stack grows downwards it might look more or less like this

<top>
|                 |
+-----------------+
| argument1       |
| argument2       |
+-----------------+
| return address  |
+-----------------+
| saved register1 |
| saved register2 |
+-----------------+
| local variable1 | <- base register
| local variable2 |
| x               |
| a               |
|                 | <- stack pointer
<bottom>

编译器会相对于某个基址寄存器为每个变量分配堆栈上的空间.当循环的范围结束时,a的空间实际上变为空闲"并可以重复使用.

The compiler assigns space on the stack to each variable relative to some base register. When the scope of the loop ends, the space for a effectively becomes "free" and can be reused.

如果稍后有第二个循环或其他嵌套范围

If there's a second loop later or some other nested scope

for (int x = 0; x < 2; x++)
{
    char * a = (char*)malloc(20);
    printf("%p\r\n", &a);
    printf("%p\r\n", a);
}
...
for (int x = 0; x < 2; x++)
{
    char * b = (char*)malloc(20);
    printf("%p\r\n", &b);
    printf("%p\r\n", b);
}

b可能会重用以前由a占用的空间,因为a不再需要它.这一切都取决于编译器如何优化堆栈上的空间.

b might reuse the space previously occupied by a, since it is not needed anymore for a. This all depends on how the compiler optimizes the space on the stack.

至少这是它对类似C语言的编译器的工作方式.当然,还有其他内存模型.

This is how it works for compiled C like languages at least. There are other memory models as well, of course.

这篇关于如果在循环内声明了指针变量,则循环的每个遍历都将其与相同的内存地址相关联吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆