c programming using a static variable and then pointing to it ? possible?
In c when creating and returning the address in a static variable inside a function would it be the same as initializing a simple
int sNum2 = 0 ; int * temp = &sNum2;
? static will basically have it's own allocated size in the memory right?
and i could just point to it from the staticNum function from now?
Maybe is not a good practice but is it ok to use?
int * staticNum(){
int static sNum=0;
int * temp=&sNum;
sNum++;
return temp;
}
This is valid code.
A static
variable, whether declared at file scope or inside of a function, has full program lifetime. That means its address will always be valid and can be safely dereferenced at any point in the program.
The returned pointer from the function
int * staticNum(){
int static sNum=0;
int * temp=&sNum;
sNum++;
return temp;
}
will be valid because the static variable sNum
will be alive after exiting the function.
Yes, it's ok to use. A pointer to a static variable, is just like any other pointer. Just pointing to the place in the data segment where the static variable is stored.