Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers for dummies

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 &num;
}

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 &num;
like image 840
Federico Gentile Avatar asked Dec 14 '22 19:12

Federico Gentile


2 Answers

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 ;
}
like image 71
2501 Avatar answered Jan 03 '23 04:01

2501


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 &num;           // therefore you have a new Int and a new a new address which is different from "i" outside this func
}
like image 38
Mads Gadeberg Avatar answered Jan 03 '23 02:01

Mads Gadeberg