简体   繁体   English

C编程中的访问指针

[英]access Pointers in C programming

I'm new to programming, and am trying to get a better understanding of pointers specifically. 我是编程的新手,正在尝试更好地理解指针。 Could a static variable be declared inside a function and then accessed or deferenced from outside the function? 可以在函数内部声明静态变量,然后从函数外部访问或引用该变量吗? Why would you not allow explicit pointers to it out of scope, since the memory of the static variable would remain allocated. 为什么您不允许超出范围的显式指针,因为静态变量的内存将保持分配状态。

Could a static variable be declared inside a function and then accessed or deferenced from outside the function? 可以在函数内部声明static变量,然后从函数外部访问或引用该变量吗?

The language allows it. 语言允许。 So, yes, you can access a pointer to it from outside the function and dereference the pointer from outside the function. 因此,是的,您可以从函数外部访问指向它的指针,并从函数外部取消引用该指针。

Why would you not allow explicit pointers to it out of scope, since the memory of the static variable would remain allocated. 为什么您不允许超出范围的显式指针,因为静态变量的内存将保持分配状态。

There are risks associated with that. 有与此相关的风险。 A calling function can change the state of the static variable. 调用函数可以更改static变量的状态。 That may or may not be OK depending on the overall structure of your program. 根据您程序的整体结构,这可能会也可能不会。

Could a static variable be declared inside a function and then accessed or deferenced from outside the function? 可以在函数内部声明静态变量,然后从函数外部访问或引用该变量吗?

Yes, you can do that. 是的,你可以这么做。

Explain the scenario where you need this, but in general I don't think its a good approach. 解释您需要此方案的情况,但总的来说,我认为这不是一个好方法。 Just declare it global. 只需将其声明为全局。

That question was part of a Homework in Programming 101 when I was in college :) 我上大学时,这个问题是编程101作业的一部分:)

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

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