#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;
}
//在上面的程序中,我试图访问局部变量c的值并将其传递给main函数并尝试在main函数中获取c变量的值。
答案 0 :(得分:2)
在函数int *changeAddress()
中,return
指向局部变量的指针 -
int c=23; //local variable which is on stack
int *ptr= &c;
一旦您的函数终止,c
的地址就会变为无效。 您只能在功能中使用此变量,而不能使用功能块 。因此,当您尝试访问无效的内存位置(未定义的行为)时,您无法在main
中获得所需的输出。
您可以重新编写程序 -
#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;
}