Jump to content

help:static array

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
csepraveenkumar

csepraveenkumar

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
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?

#2
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts

csepraveenkumar said:

can an array declared as static in one function be accessed by another function by means of pointers?
Yes.

(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?
Copy. (Assuming C, which only has pass-by-value. C++ can be different.)

#3
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,715 posts

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
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts

Quote

can an array declared as static in one function be accessed by another function by means of pointers?
I think that's what he was asking. :)
Wow I changed my sig!

#5
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,715 posts
Eh...it's kinda ambiguous, at least to me. Can't hurt to show examples of both, now can it?
sudo rm -rf /