Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer persistence in C?

Tags:

c

scope

pointers

#include <stdio.h>
int main(int argc, char * argv[])
{
    int *ip;
    printf("%d\n", *ip);
    ip=NULL;

        if (1)
        {
            int i=300;
            printf("Inside If Block \n");
            ip=&i;
            printf("*ip=%d----------\n", *ip);
        }
    //printf("i=%d\n", i); /* Now this will cause an error, i has Block scope, fair enough */
    printf("*ip=%d\n", *ip);    
    return 0;
}      

How come the last printf() returns the correct value of i?
Is it because the memory location still holds the value, even if i went out of scope? How does it work ?


1 Answers

The local variable i is out of scope, so cannot be accessed, but by chance its memory location on the stack, stored in ip, has not been overwritten. You absolutely cannot rely on this behaviour, but in practice you'll find it holds true on many platforms.

like image 122
Graham Borland Avatar answered Aug 01 '26 19:08

Graham Borland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!