Ben Bacarisse
7/13/2011 12:06:00 PM
Malcolm McLean <malcolm.mclean5@btinternet.com> writes:
> On Jul 13, 12:05Â am, Jack <spamt...@trashcan.invalid> wrote:
>> Hello. I have a few questions about allocating memory to a 32k (approx)
>> character buffer declared as:
>>
>> Â Â Â Â char string [415] [78]; Â Â Â
>>
> Multi-dimensional arrays are basically broken in C.
>
> You can declare a 2d array of size fixed at compile time, but you
> almost never want to do that. Normally you want to allocate
> dynamically. If the x dimension is known, it can be done, but the
> syntax is so strange as to make the program unreadable. If you know
> neither dimension, it can't be done.
[I assume you mean "know at compile-time" rather than "know". If you
don't know either size of the array even at run-time you can't do much
at all, including your proposal here:]
> The simple answer is to allocate the array uing the expression ptr =
> malloc(width * height * sizeof(type));
To the OP: if you want to try this unreadable syntax for something that
can't be done, try this:
type (*dynamic_array)[width] = malloc(sizeof(type[height][width]));
or if you want to use the common malloc idiom that avoids repeating the
type (and in this case, also the width):
type (*dynamic_array)[width] = malloc(height * sizeof *dynamic_array);
> Then address each element ptr[y * width + x].
which you can now address like this:
dynamic_array[y][x]
You can even pass these things to functions that can deal with arrays of
arbitrary dimensions.
This needs C99's variably modified arrays which is presumably what
Malcolm McLean was taking about when he said it can't be done. You
can't do the above in C90.
<snip>
--
Ben.