You are not logged in.
Pages: 1
While programming a stack in C, I saw an example where the pop method was void and a pointer was passed to it. I thought this was a little weird, because my first instinct would be to just return a pointer. I was wondering if this was common practice or if one of these methods was considered more appropriate than the other.
As an example of the two styles I'm talking about:
1 #include <stdio>
2
3 int *foo1(int in);
4 void foo2(int in, int *ptr);
5
6 int main(void){
7 int *ptr, *ptr2, in = 5;
8
9 ptr = foo1(in);
10 foo2(in, ptr2);
11
12 printf("%d %d n", *ptr, *ptr2);
13 }
14
15 int *foo1(int in){
16 int *ptr;
17 *ptr = (in + 2);
18
19 return ptr;
20 }
21
22 void foo2(int in, int *ptr){
23 *ptr = (in + 2);
24 }
Also, is it possible to return the address of a local variable? I ran into this example:
typedef struct {float x,y,z;} COORD;
main()
{ COORD p1, *coord_fn();
/* declare fn to return ptr of
COORD type */
....
p1 = *coord_fn(...);
/* assign contents of address returned */
....
}
COORD *coord_fn(...)
{ COORD p;
.....
p = ....;
/* assign structure values */
return &p;
/* return address of p */
}
But when I did something similar to test it, it threw a warning:
warning: function returns address of local variable
Is there a way to bypass these warnings with the compiler?
Thanks guys.
Offline
If you pass the address of a local variable, then (as far as I know) it won't work, as when the function ends, the variable is no longer there. You could do this, and it should work:
COORD *coord_fn(COORD *p,...)
{
p = ...;
.......
return &p;
}
If it doesn't, I'm blaming being tired
As for returning void and passing a pointer, I personally prefer this to returning a pointer. But it took me a while to get used to it...
Desktop: AMD Athlon64 3800+ Venice Core, 2GB PC3200, 2x160GB Maxtor DiamondMax 10, 2x320GB WD Caviar RE, Nvidia 6600GT 256MB
Laptop: Intel Pentium M, 512MB PC2700, 60GB IBM TravelStar, Nvidia 5200Go 64MB
Offline
Pages: 1