got a weird error. Does someone know what the problem might be?
The first step of finding out the reason for a weird error is to read the error message. It often explains the reason.
How can you return an array from a function in c++
You cannot return an array from a function in C++.
You can however return a class object, and class can contain an array as a member. As such by wrapping an array in a class and returning instance of that class, you can get around the restriction. There is a generic template for such array wrapper in the standard library. It is called std::array
. std::array
is limited to compile time constant size, just like array variables (see below).
int * range(/*...*/){
// ...
int ran [max] ;
// ...
return ran;
}
The problem with this is that the array is an automatic variable. The lifetime of automatic variables end when they go out of scope. Thus, the array doesn't exist after the function returns.
Returning a pointer to an automatic variable is pointless, because the pointed object never exists outside the function. Attempting to access the object through the pointer will result in undefined behaviour. You should always avoid undefined behaviour. It is bad.
Don't forget to use compiler warnings. This is what my compiler says:
warning: address of local variable 'ran' returned [-Wreturn-local-addr]
10 | return ran;
| ^~~
int * range(int max){
// ...
int ran [max] ;
The size of an array variable must be a compile time constant in C++. A function parameter is not compile time constant. Thus, this program is ill-formed.
Don't forget to use compiler warnings. This is what my compiler says:
warning: ISO C++ forbids variable length array 'ran' [-Wvla]
5 | int ran [max] ;
| ^~~
If you need to create a dynamic array, then you must allocate it dynamically. The simplest and the most convenient way to create a dynamic array is to use std:vector
.
It should do the same thing as the range() function in python
Note that python range doesn't return a list (since python 3). It returns a lazy generator range. This would also be the recommended approach in C++, instead of returning a vector.
Lazy ranges are a bit too advanced to implement for beginners, but instead of implementing it yourself, I recommend using the standard library:
for (int i : std::views::iota(0, 5))
std::cout << i << " ";
#include "iostream"
Minor issue: #include <iostream>
should conventionally be used with standard headers. Otherwise you may get surprising results if there happens to be a file named iostream
in your include path. That said, try to avoid having a file named iostream
in your include path as well (besides than the standard one).