Your approach is definitely heading in the right general direction.
I think this:
a=(double**) malloc((lx+2)*sizeof(double));
would normally be:
a = malloc(lx * sizeof(double *));
And then without the contiguity requirement, this:
a[0]= (double*) malloc((lx+2)*(ly+2)* sizeof(double));
in most programs would look like:
a[0] = malloc(ly * sizeof(double));
And finally, that last line needs to be in a loop that assigns each a[i]
with it's own malloc'ed space.
However, that won't create contiguous memory. To do that you will need to do that big allocation and then divide it up for the row vector. So, instead of the second malloc in a loop, perhaps something like:
double *t = malloc(lx * ly * sizeof(double));
for (i = 0; i < lx; ++i)
a[i] = t + i * ly;
Putting it all together:
#include <stdio.h>
#include <stdlib.h>
void arrayDemo(int lx, int ly)
{
double **a;
int i, j;
a = malloc(lx * sizeof(double *));
double *t = malloc(lx * ly * sizeof(double));
for(i = 0; i < lx; ++i)
a[i] = t + i * ly;
for(i = 0; i < lx; ++i)
for(j = 0; j < ly; ++j)
a[i][j] = i*100 + j;
for(i = 0; i < lx; ++i) {
for(j = 0; j < ly; ++j)
printf(" %4.0f", a[i][j]);
printf("
");
}
}
int main(int ac, char **av)
{
arrayDemo(atoi(av[1]), atoi(av[2]));
return 0;
}
$ cc -Wall all.c
$ ./a.out 4 7
0 1 2 3 4 5 6
100 101 102 103 104 105 106
200 201 202 203 204 205 206
300 301 302 303 304 305 306
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…