C - Returning a pointer from a function


Functions can return a memory location as a value.

Declare the function as being of a pointer type, such as

char *monster(void) 

The monster() function is declared and requires no arguments but returns a pointer to a char array - a string value.

The following code reverses a String and return the result as pointer.


#include <stdio.h> 

char *strrev(char *input); 

int main() //from  w ww.  jav  a2  s .c  om
    char string[64]; 

    printf("Type some text: "); 


char *strrev(char *input) 
   static char output[64]; 
   char *i,*o; 

   i=input; o=output; 

   while(*i++ != '\n') 

   while(i >= input) 
       *o++ = *i--; 
   *o = '\0'; 



From prototype the strrev() function we can see that it returns a pointer, the address of a char array or string.

The strrev() function requires a char pointer as its argument.

The output buffer is created and it's static, so it doesn't go away when the function is returned.

The first while loop finds the newline character at the end of the input string.

The i variable marches through the string one character at a time.

Related Topic