0
#include <stdio.h>

int *changeAddress(){


     int c=23;  
        int *ptr= &c;
        printf("Inside function Address of Pointer is %p\n",ptr);
        printf("Inside function Value of of Pointer is %d\n",*ptr);
        return (ptr);

}
int main(void){


     int *b=changeAddress();
        printf("Inside main Address of Pointer is %p\n",b);
        printf("Inside main Value of of Pointer is %d\n",*b);
        return 0;

}

//In the above program i am trying to access the value of local variable c and pass it to the main function and trying to get back the value of c variable in the main function.

shek
  • 7
  • 1
  • 4

1 Answers1

2

In function int *changeAddress() you return pointer to an local variable -

int c=23;           //local variable which is on stack
int *ptr= &c;

Address of c becomes invalid as soon as your function terminates . You can use this variable only inside your function and not out of your function blocks . Therefore, you don't get desired output in main , as you try to access an invalid memory location (undefined behaviour).

You can re-write your program -

#include <stdio.h>
#include <stdlib.h>
int *changeAddress(){
    int c=23;  
    int *ptr= malloc(sizeof(int));           //allocate memory to pointer
    if(ptr==NULL)                            //check if pointer is NULL
            return NULL;
    *ptr=c;
    printf("Inside function Address of Pointer is %p\n",ptr);
    printf("Inside function Value of of Pointer is %d\n",*ptr);
    return (ptr);
  }
int main(void){
    int *b=changeAddress();
    if(b==NULL)                             //check if return is NULL
         return 1;
    printf("Inside main Address of Pointer is %p\n",b);
    printf("Inside main Value of of Pointer is %d\n",*b);
    free(b);                                 //free allocated memeory
    return 0;
}
ameyCU
  • 16,489
  • 2
  • 26
  • 41