Как в С возвратить массив из функции?
![]()
Если на минутку исключить из рассмотрения трюк с заворачиванием массива в struct , то в языке С невозможно буквально вернуть массив из функции (или передать массив в функцию). Массивы в С являются некопируемыми объектами — их нельзя никуда «передать» и ниоткуда «вернуть». Передавать или возвращать вы можете только указатели на массивы (на сами массивы или на их элементы).
По этой причине когда говорят о «возвращении массива из функции» в контексте языка С обычно понимают следующие варианты:
Возвращение указателя на массив (на начало массива). Возвращаемый указатель не может указывать на автоматический массив, объявленный внутри этой функции, так как такой массив будет уничтожен при выходе из функции.
Возвращаемый указатель может указывать на динамически выделенную память
В таком случае освобождение выделенной памяти — обязанность вызывающего кода.
Либо он может указывать на массив со статическим временем жизни
Большим недостатком такого варианта является то, что он нереентерабелен, но и у него (в различных вариациях) есть свои применения.
Массив передается в функцию снаружи и о его создании и удалении заботится именно вызывающий код. А функция занимается лишь заполнением массива
Если вам так больше нравится, вы можете сделать и так
Ну и в качестве побочного варианта можно вспомнить об упоминавшемся выше варианте с заворачиванием массива в структуру. Такой вариант применяется редко и как правило имеет смысл лишь для массивов небольшого размера, которые всегда используются целиком
Основным вариантом «возвращения массивов» в языке С является именно вариант номер 2. А вариант 1 при желании можно реализовать в виде надстройки над вариантом 2.
Как вернуть массив из функции c
Warning:
The above program is WRONG. It may produce values of 10 or 20 as output or may produce garbage values or may crash. The problem is, that we return the address of a local variable which is not advised as local variables may not exist in memory after the function call is over.
Following are some correct ways of returning an array

1. Using Dynamically Allocated Array
Dynamically allocated memory (allocated using new or malloc()) remains there until we delete it using the delete or free(). So we can create a dynamically allocated array and we can delete it once we come out of the function.
How to Return an Array in a C++ Function

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Introduction
In this tutorial, we are going to understand how we can return an array from a function in C++.
Methods to Return an Array in a C++ Function
Typically, returning a whole array to a function call is not possible. We could only do it using pointers.
Moreover, declaring a function with a return type of a pointer and returning the address of a C type array in C++ doesn’t work for all cases. The compiler raises a warning for returning a local variable and even shows some abnormal behavior in the output.
Hence, returning an array from a function in C++ is not that easy. But we can accomplish that by following any of the below mentioned methods.
Let’s get right into it.
1. Using Pointers
As we mentioned earlier, returning a normal array from a function using pointers sometimes gives us unexpected results. But this behaviour and warnings can be avoided by declaring the array to be a static one.
Output:
Here, we have declared the function demo() with a return type int * (pointer) and in its definition, we have returned a (serves as both array name and base address) to site of the function call in main() .
As we can see from the above output, the array is successfully returned by the function.
2. Using a Structure in C++
We can also make a function return an array by declaring it inside a structure in C++. Let us see how.
Output:
Here, note that we have declared the array arr inside the structure demo . And this time the function has a return type of the structure itself and return demo_mem (structure variable) instead of the array.
In this way using another structure variable a , we can access the array arr in the main() function.
3. Using std::array
For std::array in C++, returning the array name from a function actually translates into the the whole array being returned to the site of the function call.
Output:
Hence it is clear from the output, that the array return by the function func() was successful.
Conclusion
So in this tutorial, we learned about the different methods by which we can return an array from a C++ function.
For any further questions, feel free to use the comments below.
References
-
— StackOverflow Question, — Journal Dev Post.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Return array in a function
I have an array int arr[5] that is passed to a function fillarr(int arr[]) :
- How can I return that array?
- How will I use it, say I returned a pointer how am I going to access it?
![]()
20 Answers 20
In this case, your array variable arr can actually also be treated as a pointer to the beginning of your array’s block in memory, by an implicit conversion. This syntax that you’re using:
Is kind of just syntactic sugar. You could really replace it with this and it would still work:
So in the same sense, what you want to return from your function is actually a pointer to the first element in the array:
And you’ll still be able to use it just like you would a normal array:
![]()
![]()
C++ functions can’t return C-style arrays by value. The closest thing is to return a pointer. Furthermore, an array type in the argument list is simply converted to a pointer.
You can improve it by using an array references for the argument and return, which prevents the decay:
With Boost or C++11, pass-by-reference is only optional and the syntax is less mind-bending:
The array template simply generates a struct containing a C-style array, so you can apply object-oriented semantics yet retain the array’s original simplicity.
![]()
![]()
In C++11, you can return std::array .
![]()
«Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things. There shall be no arrays of functions, although there can be arrays of pointers to functions.»
the answer may depend a bit on how you plan to use that function. For the simplest answer, lets decide that instead of an array, what you really want is a vector. Vectors are nice because the look for all the world like boring, ordinary values you can store in regular pointers. We’ll look at other options and why you want them afterwards:
This will do exactly what you expect it to do. The upside is that std::vector takes care of making sure everything is handled cleanly. the downside is that this copies a very large amount of data, if your array is large. In fact it copies every element of the array twice. first it copies the vector so that the function can use it as a parameter. then it copies it again to return it to the caller. If you can handle managing the vector yourself, you can do things quite a bit more easily. (it may copy it a third time if the caller needs to store it in a variable of some sort to do more calculation)
It looks like what you’re really trying to do is just populate a collection. if you don’t have a specific reason to return a new instance of a collection, then don’t. we can do it like this
this way you get a reference to the array passed to the function, not a private copy of it. any changes you make to the parameter are seen by the caller. You could return a reference to it if you want, but that’s not really a great idea, since it sort of implies that you’re getting something different from what you passed.
If you really do need a new instance of the collection, but want to avoid having it on the stack (and all the copying that entails), you need to create some kind of contract for how that instance is handled. the easiest way to do that is to use a smart pointer, which keeps the referenced instance around as long as anyone is holding onto it. It goes away cleanly if it goes out of scope. That would look like this.
For the most part, using *myArr works identically to using a plain vanilla vector. This example also modifies the parameter list by adding the const keyword. Now you get a reference without copying it, but you can’t modify it, so the caller knows it’ll be the same as before the function got to it.
All of this is swell, but idiomatic c++ rarely works with collections as a whole. More normally, you will be using iterators over those collections. that would look something more like this
Using it looks a bit odd if you’re not used to seeing this style.
foo now ‘points to’ the beginning of the modified arr .
What’s really nice about this is that it works equally well on vector as on plain C arrays and many other types of collection, for example
Which now looks an awful lot like the plain pointer examples given elsewhere in this question.