Can I access the static variable using the global pointer?
//In main.c file
static int c = 20; #Static vairble
int *ptr = &c; #Global pointer variable
int main(){
fun();
printf("%d\n", c);
}
//In sub.c file
extern int *ptr;
void fun(){
++*ptr;
}
When I tried to access the *ptr global variable using the extern keyword in another file I'm able to access the static variable c and even the changes made on the *ptr is reflecting on c in main.c file
Why does "ptr" not loses its global property even after its assigned by a static variable address?
Does static and global are stored in two different segments of memory or they both share the same data segment of memory?
Can global variables store non-constant values?
static is not about laying the object into a portion of memory that cannot be altered /addressed from other translation units. It is just about defining that the object has internal linkage and therefore cannot be grabbed by other translation units through this (internal) name.
But if you somehow get the memory address of an object declared static in another translation unit, you may legally access the object.
So your construct is valid.
One might just obey the "static initialization order fiasco" when other translation units draw copies of your ptr (probably before this got pointed to c).
Consider, for example, what might happen when another translation unit contains at file scope...
extern int *ptr;
int *myPtr = ptr;
...
int main() {
int x = *myPtr;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With