pointers - How to access a dynamic array in two different functions c++ -
i need access dynamic array in 2 different functions. changes made in 1 need transfer on other.
these functions:
void populate(int size, int *ptr) { ptr = new int[size]; (int = 0; < size; i++) { ptr[i] = rand() % 51; } } void display(int size, int *ptr) { (int i=0; < size; i++) { cout << ptr[i] << endl; } }
it called in main
int* ptr = null;
in populate
, attempting make pointer pass function point dynamically allocated array. pass pointer value. has no effect on caller side, , results in memory leak. need pass either pointer reference:
void populate(int size, int*& ptr) ^
or return it
int* populate(int size) { int* ptr = new int[size]; .... return ptr; }
but easiest , safest thing use std::vector<int>
both functions instead. example
std::vector<int> populate(size_t size) { std::vector<int> v(size); (auto& : v) { = rand() % 51; } return v; } void display(const std::vector<int>& v) { (auto : v) { std::cout << ptr[i] << std::endl; } }
this way, clear being returned, , caller doesn't have read on whether have manage resources pointed @ raw pointer.
note populate
can replaced call std::generate
, , display
call std::copy
.
Comments
Post a Comment