Thread: returning a string by value??

  1. #1
    Unregistered
    Guest

    Question returning a string by value??

    how do u return a string by value??

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Declare the function to return a pointer to char, that way you can return the first element of the string.
    Code:
    char * function ( char * a )
    {
      return a;
    }
    -Prelude
    My best code is written with the delete key.

  3. #3
    Unregistered
    Guest

    Question

    but that does not return the value it returns a pointer to the value, which would not work if u are returning a local varible within the function

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >but that does not return the value it returns a pointer to the value
    Which is still returning by value, and the only way you can return a string in C. If you are returning a local variable, either declare the variable as static, allocate memory for it, or let the calling function send you a buffer to hold the string.

    An alternative is to wrap the string in a structure and return that.
    Code:
    #include <stdio.h>
    
    typedef struct
    {
      char temp[BUFSIZ];
    } WRAP;
    
    static WRAP returnString ( void )
    {
      WRAP t = {"This is a string"};
      return t;
    }
    
    int main ( void )
    {
      WRAP ret;
      ret = returnString();
      puts ( ret.temp );
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  2. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  3. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM