【问题标题】:static variable and pointer to static variables in c/c++c/c++中的静态变量和指向静态变量的指针
【发布时间】:2020-09-20 08:41:09
【问题描述】:
如果我有静态变量:
static int a;
我想要一个指向这个变量的指针,指针应该是这样的:
static int* f;
f=&a;
如果我将这个 f 返回到一个函数调用,并带有一个指向静态 int* 类型指针的赋值语句,这个变量是否可以在该函数中访问?
还有:
int a;
static int* f;
f=&a; // does this mean now a is a static variable and it will be retained until the program ends?
static int b;
int* c;
c=&n; // is this possible?
【问题讨论】:
标签:
c
pointers
static
storage-class-specifier
【解决方案1】:
int a;
static int* f;
f=&a; // does this mean now a is a static variable and it will be retained until the program ends?
“[D]这意味着现在 a 是一个静态变量”?
不,它没有。 static 属性仅适用于您明确定义为static 的变量。在上面的例子中,只有f 是static。 a 的生命周期将在其周围范围结束时结束,此时指向它的任何指针都将无效。
static int b;
int* c;
c=&n; // is this possible?
“[我]这可能吗?”
是的,没关系。局部静态变量的生命周期是程序的整个生命周期。全局变量(静态或非静态)也有整个程序的生命周期。这意味着指向它们的指针将始终保持有效。
This storage-class specifier reference 可能有助于通读。