Reputation: 205
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
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
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
Reputation: 61920
You can write your own routine to resize the array.
If you want a resized block with size N
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