two-dimensional C array and its analog in D

Ali Çehreli acehreli at yahoo.com
Wed Aug 8 08:21:36 PDT 2012


On 08/08/2012 07:12 AM, Alexandr Druzhinin wrote:
 > 08.08.2012 16:29, bearophile пишет:
 >>> That C code doesn't look correct, because the given data contains no
 >>> pointers.
 >>
 >> But this C code compiles:
 >>
 >>
 >> void foo(const void** data) {}
 >> int data[2][3];
 >> int main() {
 >> foo(data);
 >> return 0;
 >> }

gcc does not accept that code:

deneme.c:18920: error: passing argument 1 of ‘foo’ from incompatible 
pointer type
deneme.c:18914: note: expected ‘const void **’ but argument is of type 
‘int (*)[3]’

 > As I know in C an array is equal to pointer,

In C and C++, an Array is automatically converted to a pointer to its 
first element.

 > so array of array == array
 > of pointers == pointer to pointer == pointer to array. Correct me if I'm
 > wrong.
 >
 > I'm trying to use OpenGL function glMultiDrawElements. It has signature:
 > void glMultiDrawElements(
 > enum mode,
 > sizei *count,
 > enum type,
 > void **indices,
 > sizei primcount
 > );

I looked at its online documentation: count is also an array that tells 
the lengths of individual rows of indices, right? So in reality the data 
is a dynamic ragged array? (I've never used that function before.)

 > If I declare indices like
 > uint[][] indices;

That's a slice of uint slices. Completely different memory layout than 
static arrays.

In any case, I am pretty sure that what you need is the .ptr property of 
D arrays. You will have to make the 'indices' parameter dynamically by 
calling .ptr on the slices.

 > then code compiles but doesn't work (but it works in C). If I do as I
 > described in the first post - it works in D. And I'd like to understand
 > the reason of it. I think the reason is difference tween C array and D
 > array, but I'm not sure.
 >
 > p.s. example of real code is too large to paste

I've started writing the following but I don't know how you are calling 
the function. Can you get this to do what you expect in C:

// WARNING: THIS C CODE DOES NOT COMPILE.
#include <stdio.h>

typedef size_t sizei;

void glMultiDrawElements(
     /* enum mode,*/
     sizei *count,
     /* enum type,*/
     void **indices,
     sizei primcount)
{
     for (size_t i = 0; i != primcount; ++i) {
         for (size_t j = 0; j != count[i]; ++j) {
             printf(" %d", indices[i][j]);
         }
         printf("\n");
     }
}

int main()
{
     /* Normally, the count array would be generated dynamically. */
     int counts[4] = { 3, 3, 3, 3 };

     int data[4][3];
     data[0][0] = 42;
     data[2][2] = 43;

     glMultiDrawElements(counts, data, 4);
}

Ali

-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html



More information about the Digitalmars-d-learn mailing list