简体   繁体   中英

How can a function returning the address of the variable return zero?

#include<stdio.h>

int *addressof();

int main()

{               
    int *p=addressof();
    printf("%u",p);
    return 0; 
}            
int *addressof()
{
    int x=9;
    
    return &x;
}

Output:

0

Can the address of the variable be zero? Is it possible?

The code you have written have undefined behavior as it returns the address of a local variable which will have been released when the function returns. In this case the compiler is can choose to optimize it and return 0.

If you change the variable to a static instead the address you return will be valid

int *addressof()
{
    static int x=9;
    
    return &x;
}

Check the warnings from your compiler, the second problem is, the size of a pointer is not necessarily the same as unsigned long , replace "%u" with "%p" in the printf .

Note: This is an addition to this answer , which covers some reason why you got zero.

Depending on your target system and its compiler, of course a variable can have an address of zero. This is the case for example on MCS51 microcontrollers, where (external) RAM starts at 0 and is used for variables. Unfortunately in that system NULL is also defined as a zero pointer, which makes common usages difficult .

printf("%p",&p);

You will get the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM