C - Returning a pointer from a function

Introduction

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.

Demo

#include <stdio.h> 

char *strrev(char *input); 

int main() /*from   ww  w. jav  a  2s. co  m*/
 { 
    char string[64]; 

    printf("Type some text: "); 
    fgets(string,62,stdin); 
    puts(strrev(string)); 

    return(0); 
 } 

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

   i=input; o=output; 

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

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

   return(output); 
}

Result

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