I would change the function to use malloc
the first time and realloc
after that.
However, there is no need to realloc
for the current elements of x
. You only need to use malloc
for the new elements of x
.
void myfunc(int n)
{
static int n0 = 0;
static double **x = NULL;
if ( n > n0)
{
if ( x == NULL )
{
// Use malloc to get memory for x
x = malloc(n*sizeof(double*));
for( int i = 0; i < n; i++)
{
x[i] = malloc(2*sizeof(double));
}
}
else
{
// Use realloc to get more memory for x.
x = realloc(x, n*sizeof(double*));
// Allocate memory only for the new elements of x.
for( int i = n0; i < n; i++)
{
x[i] = malloc(2*sizeof(double));
}
}
n0 = n;
}
}
PS Don't cast the return value of malloc
or realloc
. See Specifically, what's dangerous about casting the result of malloc? to understand why.
After a little bit of thought, I realized the function can be simplified a bit.
void myfunc(int n)
{
static int n0 = 0;
static double **x = NULL;
if ( n > n0)
{
if ( x == NULL )
{
// Use malloc
x = malloc(n*sizeof(double*));
}
else
{
// Use realloc
x = realloc(x, n*sizeof(double*));
}
// Use malloc for the new elements of x.
// When n0 is 0, it will be all of them.
for( int i = n0; i < n; i++)
{
x[i] = malloc(2*sizeof(double));
}
n0 = n;
}
}