returning a string by value??

This is a discussion on returning a string by value?? within the C Programming forums, part of the General Programming Boards category; how do u return 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,796
    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,796
    >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, 10:20 AM
  2. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 10: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21