Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to re-define an array in c++?

Tags:

c++

arrays

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?

like image 878
Cyh1368 Avatar asked Dec 13 '22 09:12

Cyh1368


2 Answers

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.

like image 120
ネロク・ゴ Avatar answered Dec 15 '22 23:12

ネロク・ゴ


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:

  • use a pointer to a dynamic array. Simple but it will require you to initialize the content of each new array. And you are supposed to take care of freeing the array before reusing the pointer - not really the C++ philosophy...
  • use a vector. Exactly the previous way but nicely encapsulated in the vector class that will take care of allocation management and current size for you
  • use one single array of the size of the longuest arrays you want to uses and copy the expected data there

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...

like image 45
Serge Ballesta Avatar answered Dec 15 '22 23:12

Serge Ballesta