On 2012-07-16,
<> wrote:
> On Mon, 16 Jul 2012 12:49:42 GMT
> Heikki Kallasjoki <fis+> wrote:
>>On 2012-07-16, Eric Sosman <> wrote:
>>> On 7/16/2012 5:23 AM, wrote:
>>>> What I'd like to do is something like:
>>>>
>>>> struct mystruct **array;
>>>>
>>>> array = (struct mystruct **)<some preallocated shared memory>
>>>> :
>>>> :
>>>> array[1][2].val = 123;
>>>>
>>>> Now I know this will crash as soon as it tries to dereference the 1st
>>>> level of the array but is there some clever way to do it?
>>>
>>> struct mystruct (*arrayptr)[18][99] = (void*)&whatever;
>>> #define array (*arrayptr)
>>> array[9][17].member= 123;
>>
>>Is there a particular reason why not simply
>>
>> struct mystruct (*thing)[99] = (void*)&whatever;
>> thing[9][17].member = 123;
>>
>>instead of the above? (Especially the #define looks really suspicious.)
>
> It'll compile but it won't work properly because it doesn't know how big
> the second dimension of the array is.
It will certainly work properly, if you use it properly:
struct mystruct (*p)[42] = malloc(33 * sizeof *p);
p[32][41].member = 123; /* furthest corner of the 33-times-42 array */
The above is completely analoguous to the one-dimensional case (except
that the elements above are 42-element arrays of struct mystruct,
whereas here they are single struct mystructs):
struct mystruct *p = malloc(33 * sizeof *p);
p[32].member = 123; /* last element of the 33-element array */
(As mentioned, the version using a pointer to a 33-times-42-sized array,
a struct mystruct (*p)[33][42], does have the advantage that sizeof *p
will yield the size of the entire array, possibly simplifying the
allocation.)
--
Heikki Kallasjoki