If you want a list of chars(array) that grows dynamically, what you need is a list of pointers where the list of each segment is a large number-say 1000. A vector container class sacrifices memory usage for the ability to grow.
vector container class allows for dynamic growth but uses a lot of memory
Also, dynamic growth one data element at a time is not recommended for a large list of data. If you want dynamic growth for a large list, create a list in chunks such as the following. Use a large list segment- of say 1000 units. I created 1000 lists in the following example. I do this by creating an array of 1000 pointers. This will create the 1 million chars you are looking for and can grow dynamically. The following example shows how you would do this.
.
void main() {
unsigned char* listsegment[1000];
int chrn=0;
int x, y = 0;
for (int x = 0; x < 1000; x++) {
listsegment[x] = new unsigned char[1000];
for (y = 0; y < 1000; y++) {
*(listsegment[x] + y) = chrn;
if (chrn >=255) chrn=0;
else chrn++;
}
}
}
Completing the program- What if more than 1000 segments need to be dynamically allocated?
Then create a list of Segment Sets. It can either be in a linked list or a in a container class.
Since the single set creates a 1000 segments of 1000 characters, a collection of these sets needs probably not be larger than 1000. A thousands sets would equal (1000*1000)*1000 which would equal one billion. Therefore, the collection would only need to be 1000 or less, which can be quickly iterated through-which makes random access for the collection not necessary.
Here is the program redone to support an infinite amount of sets through an infinitely large collection of sets. This also is a good example of segmented dynamic memory allocation in general.
#include <iostream>
#include<queue>
using namespace std;
struct listSegmentSetType {
unsigned char* listSegment[1000];
int count=0;
};
void main() {
listSegmentSetType listSegmentSet;
queue<listSegmentSetType> listSegmentSetCollection;
int numberOfListSegmentSets = 0;
int chrn = 0;
int x, y = 0;
listSegmentSet.count = 0;
for (int x = 0; x < 1000; x++) {
listSegmentSet.listSegment[x] = new unsigned char[1000];
for (y = 0; y < 1000; y++) {
*(listSegmentSet.listSegment[x] + y) = chrn;
if (chrn >= 255) chrn = 0;
else chrn++;
}
listSegmentSet.count++;
}
// add just completely filled out first list segment set to que
listSegmentSetCollection.push(listSegmentSet);
numberOfListSegmentSets++;
// now fill in second set of list segments-
listSegmentSet.count = 0;
for (int x = 0; x < 1000; x++) {
listSegmentSet.listSegment[x] = new unsigned char[1000];
for (y = 0; y < 1000; y++) {
*(listSegmentSet.listSegment[x] + y) = chrn;
if (chrn >= 255) chrn = 0;
else chrn++;
}
listSegmentSet.count++;
}
listSegmentSetCollection.push(listSegmentSet);
numberOfListSegmentSets++;
// now fill out any more sets of list segments and add to collection
// only when count listSegmentSet.count is no
// longer less than 1000.
}