Is it possible to return an array from a function?

C

chming

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
 
J

John Valko

chming said:
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
 
D

dandelion

John Valko said:
chming wrote:
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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top