so I need to allocate an array of int inside a function. The array is declared before calling the function (I need to use that array outside the function) and the size is determined inside the function. Is it possible ? I have been trying a lot of thing but nothing worked so far.
Thanks for your help guys ! Here is some code :
void fillArray(int *array)
{
int size = ...//calculate size here
allocate(array, size);
//....
}
void alloc(int * &p, int size)
{
p = new int[size];
}
int main()
{
//do stuff here
int *array = NULL;
fillArray(array);
// do stuff with the filled array
}
If I have understood correctly you did not declare an array before calling the function. It seems that you declared a pointer to int instead of an array. Otherwise if you indeed declared an array then you may not change its size and allocate memory in the function.
There are at least three approaches to do the task. The first one looks like
And the functionn is called like
The other approach is to declare a parameter of the function as having type of pointer to pointer to int. For example
and the function can be called like
The third approach is to use reference to pointer as the function parameter. For example
and the function is called like
The better way is to use standard class
std::vector<int>
instead of a pointer. For exampleand the function can be called like
Also you could use a smart pointer like
std::unique_ptr