开发者

static lifetime

开发者 https://www.devze.com 2023-01-21 10:53 出处:网络
I have a problem regarding static variables. It is said that the life of the static variable is beyond the bounds of the function (if defined in a function). But a pointer to it must give the value if

I have a problem regarding static variables. It is said that the life of the static variable is beyond the bounds of the function (if defined in a function). But a pointer to it must give the value if it exits. But it does not work.

#include<stdio.h>
int *p;
i开发者_StackOverflownt main()
{
    clrscr();
    test();
    printf("%d",*p);
    return 0;
}

void test(void)
{
    static int chacha=0;
    p=&chacha;
}


It doesn't look like you declared p anywhere.

Try this in test:

int* test(void)
{
    static int chacha = 0;
    return &chacha;
}

Now if your main is:

int main()
{
    int *p;
    clrscr();
    p = test();
    printf("%d",*p);
    getch();
    return 0;
}

you'll see the behavior you expect.


int *p;

int main()
. . .
. . .
. . .
p = &chacha;
0

精彩评论

暂无评论...
验证码 换一张
取 消