How to Expand an Array Dynamically in C++? {Like in Vector }

How to expand dynamically allocated array in C++?

If you really need not to use std::vector (for educational reasons), then your problem is here:

for(int i=0; i<brojUnesenih; ++i){
delete nizKompl[i];
}

you just copied those pointers to your new, slightly bigger array. If you delete the objects they point to, your new array is full of unusable dangling pointers.

The proximate fixes are:

  1. just don't delete these objects. Consider ownership transferred to the new array and keep them alive. Delete the three lines quoted above.
  2. OR if you really want to delete the originals, you need to copy them first - this means a deep copy of the object rather than a shallow copy of the pointer, so your new array should be populated like

    // shallow copy:
    // copy(nizKompl, nizKompl+brojUnesenih, nizTemp);
    // deep copy:
    transform(nizKompl, nizKompl+brojUnesenih, nizTemp, clone);

    with the function

    ComplexNumber* clone(ComplexNumber *original) {
    return new ComplexNumber(*original);
    }

    NB. I can't think of any good reason to do this, it's just wasteful.

C dynamically growing array

I can use pointers, but I am a bit afraid of using them.

If you need a dynamic array, you can't escape pointers. Why are you afraid though? They won't bite (as long as you're careful, that is). There's no built-in dynamic array in C, you'll just have to write one yourself. In C++, you can use the built-in std::vector class. C# and just about every other high-level language also have some similar class that manages dynamic arrays for you.

If you do plan to write your own, here's something to get you started: most dynamic array implementations work by starting off with an array of some (small) default size, then whenever you run out of space when adding a new element, double the size of the array. As you can see in the example below, it's not very difficult at all: (I've omitted safety checks for brevity)

typedef struct {
int *array;
size_t used;
size_t size;
} Array;

void initArray(Array *a, size_t initialSize) {
a->array = malloc(initialSize * sizeof(int));
a->used = 0;
a->size = initialSize;
}

void insertArray(Array *a, int element) {
// a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
// Therefore a->used can go up to a->size
if (a->used == a->size) {
a->size *= 2;
a->array = realloc(a->array, a->size * sizeof(int));
}
a->array[a->used++] = element;
}

void freeArray(Array *a) {
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}

Using it is just as simple:

Array a;
int i;

initArray(&a, 5); // initially 5 elements
for (i = 0; i < 100; i++)
insertArray(&a, i); // automatically resizes as necessary
printf("%d\n", a.array[9]); // print 10th element
printf("%d\n", a.used); // print number of elements
freeArray(&a);

Is there a way to expand a dynamic memory array in C++?

You cannot expand this type of a dynamic memory array. You can use malloc and realloc though if you need this facility but I would advice against that and suggest including <vector> and using std::vector instead. It has a resize method.

Also, what you described won't compile. The following will:

1: int *a = new int[5];
2: a = new int[2];

The above will allocate two memory blocks, neither of which will be destroyed. Second line will simply assign a new array to the same int *a pointer. When an allocated memory stops being referenced by any pointer, this is called a memory leak. The above code loses any reference to new int[5] and there is no way to free this memory to the operating system.

Although this is not a very practical example, there are multiple ways to resize an array/vector.
As it is usually practical to increase the array size, I will do just this:

{ // C++ vector on the stack (although internally vector uses memory from the heap)
std::vector<int> a(1024);
// do smth
a.resize(4096); // note: this does not always reallocate
// do smth else
}

{ // C++ everything on the heap
std::vector<int> *a = new std::vector<int>(1024);
// do smth
a->resize(4096); // note: this does not always reallocate
// do smth else
delete a;
}

{ // C style
int *a = (int*)malloc(1024*sizeof(int));
// do smth
a = realloc(a, 4096*sizeof(int));
// do smth else
free(a);
}

It is worth to note that realloc does not do anything smart. All it does is:

  • Allocate new memory block malloc
  • Copy data from old memory block to new memory block memcpy
  • Free old memory block free
  • Return new memory block

how to expand an array based on user input in c

For starters this call of the function realloc

int *ptr = realloc((size)*sizeof(int));

is incorrect. The function expects two arguments.

If you want to write a function that changes the size of a dynamically allocated array then it can look the following way

int resize( int **a, size_t n )
{
int *tmp = realloc( *a, n * sizeof( int ) );

if ( tmp != NULL ) *a = tmp;

return tmp != NULL;
}

and the function can be called for example like

do {
n1 = -1;
printf("Input the increase size of the array: ");
scanf("%d", &n1);
} while ( n1 != -1 && resize( &ptr, size += n1 ) );


How to dynamically increase the array size?

You can't change the size of the array, but you don't need to. You can just allocate a new array that's larger, copy the values you want to keep, delete the original array, and change the member variable to point to the new array.

  1. Allocate a new[] array and store it in a temporary pointer.

  2. Copy over the previous values that you want to keep.

  3. Delete[] the old array.

  4. Change the member variables, ptr and size to point to the new array and hold the new size.

C++: How to apply changes to dynamic array cross functions?

You have to pass a reference to a pointer to your function:

void addCoffee(Coffee *&c, int &amount){
// ^^ c is input and output
string name;
amount++;
Coffee * temp = new Coffee[amount];

for(int i=0;i<amount-1;i++){
temp[i] = c[i];
}

cout<<"What is the coffee's name?: ";
cin>>name;
temp[amount-1].setName(name);

delete [] c; // delete old array
c = temp; // assign new array pointer to c
}

But I recommend to use std::vector instead of dynamic arrays.

void addCoffee( std::vector<Coffee> &c ){

cout<<"What is the coffee's name?: ";
cin>>name;
c.push_back( Coffee( name ) );
}

How to extend a dynamically allocated array

You can't directly obtain new memory that is contiguous to an already allocated block. Everything is opaque and managed by the operating system and your application RTL's memory manager framework.

I see 2 possible approaches:

  • allocate a larger block using new[], copy the existing data into it, and then delete the original block using delete [].
  • use C memory allocation functions (malloc / calloc) for your internal buffer so that you can then use realloc to extend it. But this could get tricky because you don't have automatic management of construction/destruction of objects contained in the buffer.


Related Topics



Leave a reply



Submit