C范围问题

ldo*_*dog 4 c scope

以下代码是否有效

int main(){
int * a = 0;
if ( !a ) {
    int b[500];
    a = b;
}

//do something with a, 
//has the array a is 
//pointing too gone out
//of scope and garbage
//or is it still fine?
}
Run Code Online (Sandbox Code Playgroud)

nos*_*nos 11

不,不是,b已超出范围,访问它(通过指针)是未定义的行为.

  • 范围仅对名称有用 - 对于分配的空间("a"指向的内容),重要的是存储持续时间,在这种情况下是相同的,但可能不在其他情况下. (3认同)