I just learned pointers and I wrote a very simple program to check out if what I understood is correct; my idea is to create a simple functions that gets as an input a integer value and returns its address.
Even though this should be the easiest thing on earth I get a warning message after compiling and I don't know why....
#include <stdio.h>
#include <stdlib.h>
// returnType functionName(type arg1, type arg2)
int* return_me(int);
int main(){
int x = 1;
int *p;
p = &x;
printf("p: %p\n", p);
p = return_me(x);
printf("p: %p\n", p);
return 0;
}
int* return_me(int num){
return #
}
I should get the same result but I don't... where am I messing up?
Here's the warning:
pointers.c: In function ‘return_me’:
pointers.c:21:2: warning: function returns address of local variable [-Wreturn-local-addr]
return #
The line
p = return_me(x);
is assigning the value of x
to the variable num
in the function, similarly to this:
int num = x ;
p = &num ;
num
is a different variable, and has a different address.
Also note that when you return its address from a function the local variable num
doesn't exist anymore and printing its address is not really defined.
Something like this:
int* return_me( int* pnum )
{
printf("%d" , *pnum ) ;
return pnum ;
}
The thing is that a parameter in c is ALWAYS copy by value.
Therefore you can only instantiate a new int and copy the value to it num
.
int x = 1; // x is an int
int* p = &x; // p is a pointer to an int
return_me(x) // here you pass the integers value as "copy by value"
Inside return_me()
int* return_me(int num){ // here you instantiate a new int "num" and copy the value from "x" to it.
return # // therefore you have a new Int and a new a new address which is different from "i" outside this func
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With