Thread: Return String from a function

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    13

    Return String from a function

    Hi:

    is it possible to return a string from a C function (such as an array: x[10])?

    Also, is it possible to return a structure from a C function?


    Thanks in advance..

  2. #2
    Registered User
    Join Date
    May 2002
    Posts
    132
    Yes it's possible to return a string from a function. Simply declare the function as a char * which would allow you to return a pointer to the desired string. It's been a long time since I've had to return a string from a function so I believe you'd have to either declare the string inside the function as a static char or use dynamic memory allocation in order to have it work (else the data inside the string could be lost as soon as the function ends). You can do the same with a structure by declaring the function as your structure type, but make sure the function is returning a pointer to the structure rather then just returning the structure.

    Hope this helps,
    Tyouk

  3. #3
    Registered User Zeeshan's Avatar
    Join Date
    Oct 2001
    Location
    London, United Kingdom
    Posts
    226
    Try this:

    Code:
    char* return_my_name()
    {
        return "zeeshan";
    }
    
    main()
    {
       printf("%s",return_my_name());
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  3. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  4. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  5. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM