Return String from a function

This is a discussion on Return String from a function within the C Programming forums, part of the General Programming Boards category; Hi: is it possible to return a string from a C function (such as an array: x[10])? Also, is it ...

  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
    Munich, Germany
    Posts
    224
    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, 02: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, 03:13 PM
  5. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM

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