Passing Pointer to a function
I am not getting the obvious output (67, 67) for this program. Why I don't get the value of the local variable of a fucntion to which i am passing a pointer. I can pass the value of a variable to a function through pointer , but not receive the value from a function through a pointer.
#include "stdio.h"
void func(int *p)
{
int i= 67;
p = &i;
printf("\nIn func() %d\n",*p);
}
void main(void)
{
int *ptr;
func(ptr);
printf("\nIn main() %d\n",*ptr);
}
Thanks,
Nishant Ghai
Re: Passing Pointer to a function
Quote:
Originally posted by Nishant Ghai
I am not getting the obvious output (67, 67) for this program. Why I don't get the value of the local variable of a fucntion to which i am passing a pointer. I can pass the value of a variable to a function through pointer , but not receive the value from a function through a pointer.
#include "stdio.h"
void func(int *p)
{
int i= 67;
p = &i;
printf("\nIn func() %d\n",*p);
}
void main(void)
{
int *ptr;
func(ptr);
printf("\nIn main() %d\n",*ptr);
}
Thanks,
Nishant Ghai
First, don't void your mains, ... int them
main should return an int.
Second, scope of the variable i, is limited to the function fun, outside of that it has no meaning neither has its address.
Third,ptr is a pointer, and is passed by value, its value in main is not changed just by passing it in a function, you can possibly change the value of what a pointer points to this way but not the pointer itself.