Originally Posted by
kevinstrijbos
simpy return &b instead of b, than you return a pointer value.
If b is an array, &b is a pointer to that array, which is not what is needed. The name of the array is already a pointer to the first element. &b just causes an unnecessary reference/dereference. Read the first paragraph of my response in post #9.
Originally Posted by
kevinstrijbos
Well, then put &b in a variable and return that variable... I don't see what's the problem here?
&b is the address of (local variable) b, whether you return it directly or put it in another variable first. The problem is, when the function is done, b no longer exists, so trying to use it's old address to reference the data in b is invalid. It's undefined behavior. That's why you need to put the 1's and 0's in something that will exist after the function is done, like a static or a buffer you passed in or allocated on the heap. If you still don't get it, run this program:
Code:
#include <stdio.h>
int *foo(void)
{
int b = 42;
return &b;
}
void bar(void)
{
char buf[] = "In bar(). I'm just a char array, unrelated to foo() or b.";
puts(buf);
}
int main(void)
{
int *ip;
ip = foo();
printf("ip contains the address of b, foo's local var. *ip = %d\n", *ip);
bar();
printf("ip still points to b, but after calling bar, *ip = %d\n", *ip);
return 0;
}
When I compile it, my compiler warns me, because it knows that what I'm doing is bad.
Code:
$ gcc -Wall -g -std=c99 foo.c -o foo
foo.c: In function ‘foo’:
foo.c:6: warning: function returns address of local variable
And running it, I get the garbage I expect:
Code:
$ ./foo
ip contains the address of b, foo's local var. *ip = 42
In bar(). I'm just a char array, unrelated to foo() or b.
ip still points to b, but after calling bar, *ip = 2514932