Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Pointer and function ??? (http://www.go4expert.com/forums/pointer-and-function-t2819/)

frizi 2Feb2007 03:09

Pointer and function ???
 
Here is the code :
Code:

#include<stdio.h>

int send() {

        int p[2]={3,5};
        // lol = &p[0];
        return &p;

}

int main() {
        int *temp=send();
        printf("value: %i | %i \n",*(temp),*(temp+1));
        return(0);

}

/*
Here is the reply from the compiler
pp.c: In function ‘send’:
pp.c:6: warning: return makes integer from pointer without a cast
pp.c:6: warning: function returns address of local variable
pp.c: In function ‘main’:
pp.c:10: warning: initialization makes pointer from integer without a cast

... what's wrong ? It's just warning msg, It realy need to be changed something, I know that I dont encapsuled the function and with the result of function "send" can be manipulated but I dont know how else I can return a array. THanks for your help.
*/

shabbir 2Feb2007 10:03

Re: Pointer and function ???
 
You are returning from the send function a pointer but the return type of send has some other views.

frizi 2Feb2007 17:12

Re: Pointer and function ???
 
THnx but even without that int before send it's not workin good, what need to be changed ? Could you be more concrete please.

shabbir 2Feb2007 17:41

Re: Pointer and function ???
 
There are more than one errors.

1. The signature should be int* send()
2. You should not be returning the address of local variable. Its not a valid pointer in the caller function.

frizi 2Feb2007 20:24

Re: Pointer and function ???
 
Code:

// something liket that ? :
#include<stdio.h>

int* send() {
        int p[2]={3,5};
        int *lol = &p[0];
        return lol;
}

int main() {
        int *temp=send();
        printf("value: %i | %i \n",*(temp),*(temp+1));
        return(0);
}

/* no error or warning message. It's bad if I use printf from send()+1. Should I use another function which shows at send()? It' working well jus't i wanna to be right. Thanks anyway :] */

DaWei 4Feb2007 00:31

Re: Pointer and function ???
 
The pointer that you return from send is a local value that goes out of scope when send returns. It is available for use by other code declaring locals. It is even available for your processor to use for tracking the flow of the program. Your program works simply because you are referring to the old area before it is reused by something else. It is a distinct no-no. It is a crash in the making. Review the concept of local variables.


All times are GMT +5.5. The time now is 01:13.