Is it possible to return an array from a function?

Discussion in 'C Programming' started by chming, Jan 14, 2005.

  1. chming

    chming Guest

    It is ok to return a struct variable from a function. How about an
    array of any type from a function?

    Because the array is allocated in the stack, it is no meaning to return
    it, which ever type it is. This array is the memory of stack.
    But for a struct, it is allocated
     
    chming, Jan 14, 2005
    #1
    1. Advertising

  2. chming

    John Valko Guest

    chming wrote:
    > It is ok to return a struct variable from a function. How about an
    > array of any type from a function?
    >
    > Because the array is allocated in the stack, it is no meaning to return
    > it, which ever type it is. This array is the memory of stack.
    > But for a struct, it is allocated
    >

    Straight from the Standard:

    6.7.5.3 Function declarators (including prototypes)

    Constraints

    [#1] A function declarator shall not specify a return type
    that is a function type or an array type.

    -- and --

    6.9.1 Function definitions

    [#3] The return type of a function shall be void or an
    object type other than array type.

    So in other words, no. You can, however, return blocks of memory
    allocated using malloc() and friends. So if you wish to return the
    contents of an array you may do so indirectly by copying it into a
    buffer allocated with malloc() and returning its address.

    --John
     
    John Valko, Jan 14, 2005
    #2
    1. Advertising

  3. chming

    dandelion Guest

    "John Valko" <> wrote in message
    news:cs7u6a$i5a$...
    > chming wrote:

    <snip>

    > So if you wish to return the contents of an array you may do so indirectly

    by copying it into a
    > buffer allocated with malloc() and returning its address.


    Of simply return a pointer to the array. Mind the scope of the array,
    though.
     
    dandelion, Jan 14, 2005
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. chming
    Replies:
    1
    Views:
    270
    Lawrence Kirby
    Jan 14, 2005
  2. Greenhorn
    Replies:
    15
    Views:
    833
    Keith Thompson
    Mar 6, 2005
  3. Replies:
    17
    Views:
    489
    Frederick Gotham
    Aug 25, 2006
  4. Replies:
    3
    Views:
    917
    Frederick Gotham
    Nov 30, 2006
  5. Davy
    Replies:
    9
    Views:
    1,473
Loading...

Share This Page