Vamsee said:
I have a 4D array:
float T[12][12][12][5]; ( have to go atleast upto T[60][60][60][2000]
if system supports)
How to malloc() it? can you please give me a brief illustration
because I haven't found any article dealing with this.
if I say
float (*T)[12][12][12][5];
T=(float *)malloc(60000);
it says "cannot convert float * to float *[12][12][12][5] "
The usual advice on comp.lang.c is "Don't cast the
result of malloc()," but here's a case where the cast
was helpful: it caused the compiler to complain, and
that drew attention to the malloc() call. Without the
cast the compiler would not have complained -- but the
malloc() call would have been incorrect anyhow, and the
error might have been harder to find.
The immediate error is that `T' is not a `float*', but
a pointer to a big 4D array of `float' objects. Removing
the cast "fixes" that problem, because malloc() returns a
`void*', which can be converted to any kind of data pointer
without explicit conversion.
The next problem is the size of the allocation. You've
asked for 60000 bytes to hold an array of 25920 elements;
that's about 2.31 bytes per element. There may be machines
somewhere where sizeof(float) is 2, but I've never encountered
one. If sizeof(float) on your machine is 4 (as is much more
common), the array needs 106380 bytes.
You can (and should) solve both of these problems with
the comp.lang.c Official Allocation Recipe:
T = malloc(sizeof *T);
However, one possible problem remains. `T' is a pointer
to a 4D array, so `*T' is the 4D array itself. That means
you can't write `T[h]
[j][k]' to access an array element;
you've got to write `(*T)[h][j][k]' instead. This may
be what you intended, but it seems unlikely.
A better way to proceed might be to make `T' be a pointer
to a 3D array, and then to allocate enough room for twelve
such arrays:
float (*T)[12][12][15];
T = malloc(12 * sizeof *T);
.... and now you can write `T[h][j][k]' the way people
usually prefer.