Why can't we inizitialize arrays with a function that returns arrays

Nov 1, 2020 at 6:32pm
So I know that

the following code doesn't technically "return" array, but I still want to know why it gives me an error when trying to to initialize/assign a value to an array?

I searched for this particular question and did not find the reason for this not working or a straightforward and detailed answer.

1
2
3
4
5
6
7
8
9
10
11
12
void testing()
{
	unsigned arr[5];
	arr = make_array(); // <----this part of the code does not work.
                            // why is that case?
}

unsigned* make_array()
{
	unsigned arr[5] = { 0,0,0,0,0 };
	return arr;
}
Nov 1, 2020 at 6:48pm
Line 10 declares and initializes an array local to the make_array function.
Once you return from that function, the array no longer exists.

The pointer to the array that you return will point to junk once the function is over, and it's undefined behavior to then use this junk pointer.

In addition to not being able to return a C-style array from a function, you also can't assign an array to another array. It just doesn't work like that.

However, if you used a std::vector or a std::array object, you could do both of these things, and it works like you'd expect.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Example program
#include <iostream>
#include <array>

std::array<int, 5> make_array()
{
    std::array<int, 5> arr;
    arr[3] = 42;
    return arr;
}

int main()
{
    std::array<int, 5> arr = make_array();
    
    arr = make_array(); // redundant; just showing you can assign to it.
   
    std::cout << arr[3] << '\n';   
}
Last edited on Nov 1, 2020 at 6:50pm
Nov 1, 2020 at 6:57pm

you also can't assign an array to another array. It just doesn't work like that.


can you please elaborate more on that please and what do you mean specifically by that as well?
Last edited on Nov 1, 2020 at 6:58pm
Nov 1, 2020 at 7:29pm
you cannot say
int x[10];
int y[10];
x = y; //no can do. you need a loop. c arrays are just blocks of memory, they have no assignment operator.

the object oriented arrays, you can do this:
vector<int> x(10);
vector<int> y(10);
x = y; //ok: vector is a class that defines an assignment operator!

that was C-arrays.
std::array does have assignment operator and many other things. It is also an object.
Last edited on Nov 1, 2020 at 7:32pm
Nov 1, 2020 at 8:57pm
Your reply still has some holes that need to be filled

and I did some searching to make this problem more relatable to others who find themselves in a similar situation

hence I'll add this

You can also use the
std::copy
function.

Also@jonnin said arrays don't have an assignment operator. For more info on that I suggest this article https://stackoverflow.com/questions/5345705/equality-assignment-operators-used-on-arrays-in-c
Nov 2, 2020 at 6:03am
Your reply still has some holes that need to be filled
-- Let's see if I can fill the holes.

Ganado has pointed out one of the key reasons that the function doesn't work, it's called 'scope' if you want a term you can search. One way around scope issues is to utilize dynamic memory, which is how a vector works (and how several C++ container classes like vector work). Key words to look up when studying dynamic memory are 'new' 'delete' 'heap' 'stack' 'vector' 'linked list' 'list' 'memory leak', 'dangling pointer'.

Once you have created a dynamically allocated array of integers, you could return a pointer to that data. That pointer can be treated as if it were the original array. Which is where pointers start to become a very light-weight tool for very powerful operations.

There is one more way to get around your scope issue, and that's to take an array or a pointer to an array as the function's argument, then just modify that existing array. No return statement would be necessary at that point.

Jonin points out another issue which C++ inherits from C, which your link to stackoverflow describes. An array can't be initialized by another array. C++ introduced classes and operator overloading and many advanced ideas, but before that it was hard to say how assignment should work on all blocks of data, so sadly they chose to avoid it completely for arrays in the original C language.

If you look at the source behind the std::copy function, it basically is going to be a loop that does what jonnin suggests. (Though they may use assembly to tap into larger data sizes such as SIMD AVX-512, this is unlikely, advantages of doing so are hindered by the ram speed bottleneck) Many times advanced coders are going to edge towards creating code that is easier to maintain rather than getting too fancy.

Ganado, Jonnin, and I all recommend you check out vectors (and other container classes), which solve the assignment operator problem. Take a day and research vectors, it sounds like you might be ready to step beyond C language ideas and into the things that C++ has to offer.

http://www32.cplusplus.com/reference/vector/
Last edited on Nov 2, 2020 at 7:30am
Topic archived. No new replies allowed.