C++ Allocate dynamic array inside a function -
so need allocate array of int inside function. array declared before calling function (i need use array outside function) , size determined inside function. possible ? have been trying lot of thing nothing worked far.
thanks guys ! here 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); // stuff filled array }
if have understood correctly did not declare array before calling function. seems declared pointer int instead of array. otherwise if indeed declared array may not change size , allocate memory in function.
there @ least 3 approaches task. first 1 looks like
int *f() { size_t n = 10; int *p = new int[n]; return p; }
and functionn called like
int *p = f();
the other approach declare parameter of function having type of pointer pointer int. example
voif f( int **p ) { size_t n = 10; *p = new int[n]; }
and function can called like
int *p = null; f( &p );
the third approach use reference pointer function parameter. example
voif f( int * &p ) { size_t n = 10; p = new int[n]; }
and function called like
int *p = null; f( p );
the better way use standard class std::vector<int>
instead of pointer. example
void f( std::vector<int> &v ) { size_t n = 10; v.resize( n ); }
and function can called like
std::vector<int> v; f( v );
also use smart pointer std::unique_ptr
Comments
Post a Comment