Thread: Doubt in C Code (printed return value of local variable's address is 0)

  1. #1
    Registered User
    Join Date
    Dec 2017
    Posts
    1

    Post Doubt in C Code (printed return value of local variable's address is 0)

    Hello Cboard members,

    I have written the following code. I am unable to understand why the returned value is 0 while in the function hi() it is non-zero.

    Code:
    #include<stdio.h>
    int* hi(void);
    int main() {
      int *Dptr;
      int n=5;
      Dptr = &n;
      printf("\n %u", Dptr);
      Dptr = hi();
      printf("\n %u", Dptr); // Why is this printed 0 on execution ?
    }
    int* hi(void)
    {
      int *Rptr;
      int n=5;
      Rptr = &n;
      printf("\n %u", Rptr);
      return &n;    
    
    
    }
    Regards,
    HitX11

  2. #2
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    The "address of" a local (non-static) variable is undefined after returning from the function; the fact that it's 0 in this case is immaterial (it could be anything it wants to be simply because it's undefined).

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Just so you know, use "%p" when printing a pointer.

    Code:
    #include <stdio.h>
    
    int main(void)
    {
        int n = 5;
        int *p = &n;
    
        printf("%p -> %d\n", (void *)p, *p);
    
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Local variable address in memory
    By bkane521 in forum Linux Programming
    Replies: 6
    Last Post: 03-03-2013, 08:10 AM
  2. warning: address of local variable ‘f’ returned
    By dayalsoap in forum C++ Programming
    Replies: 9
    Last Post: 07-20-2011, 10:51 PM
  3. Replies: 4
    Last Post: 07-11-2011, 10:50 AM
  4. Returning the Address of a Local Variable (Array)
    By Jesdisciple in forum C Programming
    Replies: 9
    Last Post: 08-20-2008, 02:03 AM
  5. return reference to local variable, good code?
    By George2 in forum C++ Programming
    Replies: 3
    Last Post: 12-17-2007, 12:34 PM

Tags for this Thread