I have an array int arr[5]
that is passed to a function fillarr(int arr[])
:
int fillarr(int arr[])
{
for(...);
return arr;
}
- How can I return that array?
- How will I use it, say I returned a pointer how am I going to access it?
I have an array int arr[5]
that is passed to a function fillarr(int arr[])
:
int fillarr(int arr[])
{
for(...);
return arr;
}
This:
is actually treated the same as:
Now if you really want to return an array you can change that line to
It's not really returning an array. you're returning a pointer to the start of the array address.
But remember when you pass in the array, you're only passing in a pointer. So when you modify the array data, you're actually modifying the data that the pointer is pointing at. Therefore before you passed in the array, you must realise that you already have on the outside the modified result.
e.g.
I suggest you might want to consider putting a length into your fillarr function like this.
That way you can use length to fill the array to it's length no matter what it is.
To actually use it properly. Do something like this:
If all you're wanting to do is set the array to some default values, consider using the built in memset function.
something like: memset((int*)&arr, 5, sizeof(int));
While I'm on the topic though. You say you're using C++. Have a look at using stl vectors. Your code is likely to be more robust.
There are lots of tutorials. Here is one that gives you an idea of how to use them. http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html
to return an array from a function , let us define that array in a structure; So it looks something like this
Now let us create variables of the type structure.
We can pass array to a function in the following way and assign value to it:
We can also return the array. To return the array , the return type of the function should be of structure type ie marks. This is because in reality we are passing the structure that contains the array. So the final code may look like this.
In C++11, you can return
std::array
.the Simplest way to do this ,is to return it by reference , even if you don't write the '&' symbol , it is automatically returned by reference
and what about:
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: