Header
//##############################################################################
// class for an array of strings that automatically expands as needed.
//##############################################################################
class string_auto_array{
private:
int _next;
int _size;
int _chunk;
char **_array;
int resize(int index);
public:
string_auto_array(int chunk = 10, int size = 10);
~string_auto_array();
int set(int index, char *value);
char *get(int index);
int get(int index, char **value);
char *&operator[] (unsigned i) { return _array[i]; }
int size() { return _size; }
int next() { return _next; }
};
Code
//##############################################################################
string_auto_array::string_auto_array(int chunk, int size)
{
_chunk = chunk;
_size = (size / _chunk + 1) * _chunk;
_next = 0;
_array = new char *[_size];
for (int i = 0; i < _size; i++) {
_array[i] = NULL;
}
// if (_array == NULL) {
// printf("array creation failed\n");
// }
}
//##############################################################################
string_auto_array::~string_auto_array()
{
int i;
printf("auto array destroyed\n");
delete[] _array;
}
//##############################################################################
int string_auto_array::resize(int index)
{
int new_size = (index / _chunk + 1) * _chunk;
// here is where we need to expand the array
// printf("resize from %d to %d\n", _size, new_size);
char **n, **o;
n = new char *[new_size];
if (n != NULL) {
// creation of new array succeeded
// copy old stuff over
int i;
for (i = 0; i < _next; i++) {
n[i] = _array[i];
}
for (; i < new_size; i++) {
n[i] = NULL;
}
// destroy old array
o = _array;
_array = n;
delete[] o;
_size = new_size;
}
else {
fprintf(stderr, "expansion of array failed\n");
exit(1);
}
}
//##############################################################################
int string_auto_array::set(int index, char *value)
{
// printf("insert %dth element..", index);
if (index >= _size) {
resize(index);
}
if (index >= _next) {
// printf("bump _next to %d, was %d\n", index + 1, _next);
_next = index + 1;
}
_array[index] = value;
// printf("_next = %d\n", _next);
}
//##############################################################################
char *string_auto_array::get(int index)
{
if (index < _next) {
return _array[index];
}
}
//##############################################################################
int string_auto_array::get(int index, char **value)
{
if (index < _next) {
*value = _array[index];
return 1;
}
else {
return 0;
}
}