Hi there
This is not an urgent question, I'm just curious to know if there is an answer. I've done a search but nothing has come up - I suspect this is because I don't know how to pose the question succinctly.
I use this function to dynamically allocate 2D arrays of type int:
Code:
int **get_space_i(int m, int n)
{
int i, *p, **a;
p = malloc(m * n * sizeof(int));
a = malloc(m * sizeof(int *));
for(i = 0; i < m; i++) a[i] = p + (i * n);
return a;
}
and this one to do the same for floats:
Code:
float **get_space_f(int m, int n)
{
int i;
float *p, **a;
p = malloc(m * n * sizeof(float));
a = malloc(m * sizeof(float *));
for(i = 0; i < m; i++) a[i] = p + (i * n);
return a;
}
and the same for doubles, structs etc. This is how it's used:
Code:
int *X, rows, cols;
X = get_space_i(rows,cols);
So I was wondering if there was a way that I could make one generic function where a third argument specifies the type? I tried something like this:
Code:
void **get_space(int m, int n, size_t size)
{
int i;
void *p, **a;
p = malloc(m * n * size);
a = malloc(m * size);
for(i = 0; i < m; i++)
{
a[i] = p + (i*n);
}
return a;
}
int **a;
float **b;
a = (int **)get_space(m,n,sizeof(int));
b = (float **)get_space(m,n,sizeof(float));
but it segfaults. Any ideas how this might work?
Thanks in advance
Gib