The C Programming Language - Pointers
This is a free tutorial about pointers from the book "The C Programming Language" by Heimo Gaicher
This is a free tutorial about pointers from the book "The C Programming Language" by Heimo Gaicher
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
1.11 Return a Pointer from Functions<br />
You already know how to declare functions with return values. If the return value is a<br />
pointer, a * is appended to the return type as usual.<br />
int* func() {<br />
…<br />
}<br />
In the following example, the address of ivar is returned as the return value:<br />
/* example 139 - return a pointer from functions */<br />
#include <br />
int* myFunction(void) {<br />
static int ivar = 100; // declare here a static variable<br />
}<br />
return (&ivar); // return the address of ivar<br />
int main (void)<br />
{<br />
int *iptr;<br />
iptr = myFunction();<br />
// function call, iptr get the address of ivar<br />
printf("Address of ivar: %p\n", iptr);<br />
printf("Value of ivar: %d\n", *iptr);<br />
*iptr = 50; // change the value of ivar to 50<br />
printf("Value of ivar: %d\n", *iptr);<br />
}<br />
return 0;<br />
Address of ivar: 0040a004<br />
Value of ivar: 100<br />
Value of ivar: 50<br />
It is important that the variable within the function is defined as a static variable,<br />
otherwise it will be destroyed when the function is exited and access to this address is<br />
no longer possible.<br />
<strong>The</strong> C <strong>Programming</strong> <strong>Language</strong> by Heimo Gaicher – Chapter <strong>Pointers</strong> 22