S
Seebs
So, for a really long time, I've done this:
int **allocate_multidim_array(int n, int m) {
int **a;
int i;
a = malloc(n * sizeof(int *));
for (i = 0; i < n; ++i) {
a = malloc(m * sizeof(int));
}
}
void free_multidim_array(int **a, int n) {
int i;
for (i = 0; i < n; ++i)
free(a);
free(a);
}
(Not really as functions, normally, just presenting them this way so
you can see the logic clearly.)
Recently, I had cause to do this, and it occurred to me I
could do something else:
int **allocate_multidim_array(int n, int m) {
int **a;
int *data;
int i;
a = malloc(n * sizeof(int *));
data = malloc(n * m * sizeof(int));
for (i = 0; i < n; ++i) {
a = data + (i * m);
}
}
void free_multidim_array(int **a, int n) {
free(a[0]);
free(a);
}
So far as I can tell, this is just plain cleaner, simpler, and so on.
Am I missing something? Is the former idiom actually widespread, or did
I just invent it wrong? Is there a benefit to it I haven't considered,
other than sparse arrays or things larger than you can allocate as a single
object?
-s
int **allocate_multidim_array(int n, int m) {
int **a;
int i;
a = malloc(n * sizeof(int *));
for (i = 0; i < n; ++i) {
a = malloc(m * sizeof(int));
}
}
void free_multidim_array(int **a, int n) {
int i;
for (i = 0; i < n; ++i)
free(a);
free(a);
}
(Not really as functions, normally, just presenting them this way so
you can see the logic clearly.)
Recently, I had cause to do this, and it occurred to me I
could do something else:
int **allocate_multidim_array(int n, int m) {
int **a;
int *data;
int i;
a = malloc(n * sizeof(int *));
data = malloc(n * m * sizeof(int));
for (i = 0; i < n; ++i) {
a = data + (i * m);
}
}
void free_multidim_array(int **a, int n) {
free(a[0]);
free(a);
}
So far as I can tell, this is just plain cleaner, simpler, and so on.
Am I missing something? Is the former idiom actually widespread, or did
I just invent it wrong? Is there a benefit to it I haven't considered,
other than sparse arrays or things larger than you can allocate as a single
object?
-s