简体   繁体   English

C中的静态局部变量地址

[英]static local variable address in C

I know that a static local variable is in existence for the life of a program. 我知道在程序的生命周期中存在一个静态局部变量。 But does a static local variable maintain the same memory address? 但静态局部变量是否保持相同的内存地址?

Or does the compiler just ensure that it exists and can be accessed within the local scope? 或者编译器是否确保它存在并且可以在本地范围内访问?

In C objects don't move around during their lifetime. 在C对象中,它们在其生命周期内不会移动。 As long as an object exists, it will have the same address. 只要存在对象,它就具有相同的地址。

Variables with static storage (this includes variables with block scope declared as static ) have a lifetime that covers the whole execution of the program, so they have a constant address. 具有静态存储的变量(这包括将块作用域声明为static变量)具有覆盖程序整个执行的生命周期,因此它们具有常量地址。

Yes, the address offset of every static variable is known at the compile time. 是的,每个静态变量的地址偏移量在编译时都是已知的。 When the binary is loaded into the memory, local variables are stored in the .data segment of the program's address space. 当二进制文件加载到内存中时,局部变量存储在程序地址空间的.data段中。

In other words, the address of a static variable won't change during the code execution. 换句话说,静态变量的地址在代码执行期间不会改变。

There's very little difference between local static s and regular globals. 局部static s和常规全局变量之间几乎没有区别。

int x = 42; //static lifetime, external name
static int y = 43; //static lifetime, no external name, 
                   //referencable in all scopes here on out
                   //(unless overshadowed)
int main()
{
   static int z = 44; //like y, but only referencable from within this scope
                      //and its nested scopes
   {
       printf("%p\n", (void*)&z));
   }
}

All of these have fixed addresses once the program has been linked and loaded. 一旦程序被链接和加载,所有这些都具有固定的地址。

Local statics are like globals, except they're only referencable (by their name) from within their scope and its nested subscopes. 局部静态就像全局变量一样,除了它们只能在它们的范围和它的嵌套子范围内引用(通过它们的名字)。 (You can refer to them from unrelated scopes via pointers.) (您可以通过指针从不相关的范围引用它们。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM