I have the following array in my program:
int foo[] = {1,2,3,4,5};
//Do something with foo, but then there's no use with it afterwards
Since I need a lot more "single-use" arrays just like this, I want to re-define it like the following:
foo[] = {5,2,3}; //Raises an error
Note the array size could vary.
The only solution I've got is to create a new array for each re-definition, but that would be too much storage.
Is there any way of re-defining? Or is there any other solutions?
As the array must be able to vary its size, you could consider using std::vector
instead of raw arrays and reassigning the vector whenever you need a new "array":
#include <vector>
#include <cassert>
int main() {
std::vector<int> foo = {1, 2, 3, 4, 5};
assert(foo.size() == 5);
foo = {5, 2, 3}; // <-- reassign
assert(foo.size() == 3);
}
The assignment replaces the vector's contents with those of the initializer list. No additional memory allocation will occur if the vector has enough capacity to store it.
Well, an array is not a first class object, but looks more like the beginning of a memory zone that will contain a sequence of objects. Because of that, the C++ does not allow to directly assign to an array. Full stop (BTW the ancestor C language does not either).
Workarounds:
In those ways (except for the vector which is much more programmer friendly, you are supposed to keep track of the current used length
But if the reason is to save memory, the simplest and most efficient way is to directly use a pointer to initialized arrays. If you can extract the initialization data at run time, it must be present somewhere since build time, so why not directly use that memory(*)? The only downside I can imagine is that you will have track the length of the pointed array.
There is one notable exception. In some embedded system, initialization data can be stored in read only memory. In that case, you cannot directly use that memory if you need to write in it...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With