can an array declared as static in one function be accessed by another function by means of pointers?
when a pointer to a variable is passed to a function, is the actual pointer passed or a copy of the pointer?
help:static array
Started by csepraveenkumar, Aug 16 2009 09:48 AM
4 replies to this topic
#1
Posted 16 August 2009 - 09:48 AM
|
|
|
#2
Posted 16 August 2009 - 10:02 AM
csepraveenkumar said:
can an array declared as static in one function be accessed by another function by means of pointers?
(Try to be a little more specific with 'static' if possible.)
csepraveenkumar said:
when a pointer to a variable is passed to a function, is the actual pointer passed or a copy of the pointer?
#3
Posted 16 August 2009 - 01:34 PM
Quote
can an array declared as static in one function be accessed by another function by means of pointers?
Not necessarily. For example:
int main(void)
{
char *p;
p = foo();
bar(p);
return 0;
}
char *foo(void)
{
char str[] = "abcdef";
return str;
}
void bar(char *ptr)
{
//FAIL - PTR DOES NOT EXIST ANYMORE
printf("%s",ptr);
}
However, this will work (though it's bad style).
int main(void)
{
char *p;
p = foo();
bar(p);
return 0;
}
char *foo(void)
{
static char str[] = "abcdef";
return str;
}
void bar(char *ptr)
{
//This is ok
printf("%s",ptr);
}
The reason is that local variables declared as static are not stored on the stack as regular locals are, so they're permanent across function calls. A non-static variable is trashed as soon as its containing function returns. The address will still be valid, but it'll point to junk.
sudo rm -rf /
#4
Posted 16 August 2009 - 01:43 PM
Quote
can an array declared as static in one function be accessed by another function by means of pointers?
Wow I changed my sig!
#5
Posted 16 August 2009 - 01:46 PM
Eh...it's kinda ambiguous, at least to me. Can't hurt to show examples of both, now can it?
sudo rm -rf /


Sign In
Create Account


Back to top









