Who Cares
Who Cares

Reputation: 205

Reallocating 2D arrays on C++

lets say i have:

#include <iostream>
using namespace std;
int **a; //Global Variable
int main()
{
   n=5;
   a = new int*[n];
   for ( int i = 0 ; i < n ; i++ ) 
   a[i] = new int[n] ;
}

is there any realloc() method to increase the row size? (column size is fixed) I mean if the row size is 5 then i wanna make it 6 not much more, just +1. I use

for(i=0;i<n;i++)
{
   counter++;
   a[i] = (int *) realloc(a[i],counter*sizeof(int));
}

but i think something is wrong....

Edit: please don't advise any vector or sth like that.. Cuz i need my array as global.

Upvotes: 0

Views: 864

Answers (3)

RED SOFT ADAIR
RED SOFT ADAIR

Reputation: 12218

The answer is No!

C++ memory management does not contain functionality for reallocating/resizing allocated memory. You would have to implement such a thing yourself using new/copy/delete semantics

Upvotes: 0

James M
James M

Reputation: 16718

realloc only works when you allocated with malloc. If you used new, you'll have to delete and then use new again (or just use something like a std::vector).

EDIT: Since you asked for an example of how to use malloc:

a = new int*[n];

would become

a = (int **) malloc (n * sizeof (int *));

and

a[i] = new int[n] ;

would become

a[i] = (int *) malloc (n * sizeof (int));

Upvotes: 4

phoxis
phoxis

Reputation: 61920

You can write your own routine to resize the array.

If you want a resized block with size N

  1. allocate (new) the new size N
  2. copy old array/block to this newly allocated array/block
  3. free the old array (delete)

To avoid calling this routine again and again, better preallocate a large chunk, the size of chunk will be determined by the need of your application, and should be such which avoid resizing the array a lot of times.

Upvotes: 0

Related Questions