I'm building an algorithm in which I want to generate some data using (for loop) and store them into array A. I created a function for generating these data and initalize it at the beginning. I won't call this function except I needed it.
The problem arise when I have other function that use data from this array A in a loop. When I used dynamic array, I should free the allocated memory which consequently delete the data stored in array A. I did not want to call the function for generating data each time in a loop as it was computationally expensive until I needed it.
arrayA = newint[size]; //the size is dynamically changing
generate_data(); // when needed
delete arrayA; // arrayA will be freed
If I use stack array, I can allocate first a huge of data storage in the beginning, and need not to be freed so I can call generata_data() as needed without losing the data in arrayA. But, it won't efficient.
But, suppose If I create a class and not function to generate and save the data. I could not pass the data (created using std::vector) in class into my other function. I mean when using class, we can't access the data that stored in vector array.
Vectors have .data() member fuction which returns pointer to underlying array. So you can pass it. And why not make other function recieve vector as well? Also use of void pointers (and raw pointers as whole) is discouraged in C++
Well, actually I'm dealing with 3D graphics library with predefined function that receive void pointer argument. .data() member is only supported in c++11 whereas my NDK do not support c++11. So what do you think would be the best way?
Before C++ 11 we used address of first element to pass underlying array: &(myvector)
And what about heap overallocation? It would save you time on allocating/freeing memory, copy and no risk of invalidating pointer to first element or memory leak.