So let's assume that you have pointer to an array and you would like to use this array into a function. Here is an example of how to correctly send the pointers to avoid memory leaks:
#include < iostream >
void modifyData(unsigned int **i_array,unsigned int short i_len)
{
(*i_array)[0] = 1;
(*i_array)[2] = 2;
}
int main(int /*argc*/, char **/*argv*/)
{
unsigned int short len = 5;
unsigned int *mydata = new unsigned int[len];
// initialise the values of the array
for(unsigned int i=0; i < len; ++i)
{
mydata[i] = 0;
}
// print the original values of the array
for(unsigned int i = 0; i < len; ++i)
{
std::cout << mydata[i] << " ";
}
std::cout << "\n";
// call function that will modify the data
modifyData(&mydata,len);
// print the new values of the array
for(unsigned int i = 0; i < len; ++i)
{
std::cout << mydata[i] << " ";
}
std::cout << "\n";
delete []mydata;
return 0;
}
No comments:
Post a Comment