Thread: How to Return Char Array in function?

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    49

    How to Return Char Array in function?

    Hi All, I want to ask about how to return the Char Array in Function, many thanks!!
    Code:
    unsigned char[] FN()
    {
    unsigned char ret[35];
    ret ="aabbccddee";
    return ret
    }
    
    Main()
    {
    unsigned char abc[35];
    abc= FN();
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    1. You cannot return an array. You can return a pointer.
    2. Returning a pointer to a non-static local array, or a pointer to an element of a non-static local array, is wrong because the array will cease to exist after the function returns.

    My guess is that what you want to do would involve passing a pointer to unsigned char to the function, then copying the desired string literal to the array of unsigned char using that pointer.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Apr 2012
    Posts
    49
    I want to code like this,
    Code:
    void FN(unsigned char output[]) { output="abcde"; } Main() { unsigned char output[100]; //<==============don't know the length of the char array unsigned char abc[35]; FN(output); printf("%s",output); }
    but I can't, as I don't know the length of the output before pass it to the function FN(), how can I pass it as dynamic char array?
    Last edited by homoon; 04-19-2012 at 10:52 PM.

  4. #4
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    O_o

    You can jump through the hoops of writing your own string type, download an existing one, or do as anyone else at your level would do and return a pointer freshly allocated by the relevant function. (`malloc'/`free')

    Soma

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can a function return char variable?
    By mystic in forum C Programming
    Replies: 10
    Last Post: 07-13-2010, 01:05 AM
  2. Replies: 3
    Last Post: 11-17-2008, 12:36 PM
  3. Replies: 22
    Last Post: 09-11-2008, 03:31 PM
  4. return char array
    By Bitphire in forum C++ Programming
    Replies: 6
    Last Post: 03-07-2005, 10:48 AM
  5. getting a function to return a char array
    By variable in forum C Programming
    Replies: 20
    Last Post: 02-10-2005, 08:13 PM