On Wed, Apr 03, 2002 at 11:15:55AM +0200, Erik Hofman wrote:
> It would be nice to see if the attached test program produces the 
> following output on all supported platforms(This would allow us to 
> improve the speed of the code dramattically by using memcpy instead of 
> for-loops):
> 
> 0       1       2       3       4       5       6       7       8       9
> 
> Erik

> 
> #include <stdio.h>
> #include <string.h>
> 
> int main () {
> 
>    int a[2][2][5];
>    int b[2][5];
>    int q;
>   
>    for (q=0; q < 10; q++) {
>       a[0][q/5][q%5] = q;
>       a[1][q/5][q%5] = q+100;
>    }
> 
>    memcpy(b, a[0], sizeof(b));
>    for (q=0; q < 10; q++)
>       printf("%i\t", b[q/5][q%5]);
> 
>    return 0;
> }

8<-----------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
        char a[2][2][5];
        char b[2][5];
        char *p;
        int index, i, j, k;

        index = 0;
        for(i = 0; i < 2; i++) {
                for(j = 0; j < 2; j++) {
                        for(k = 0; k < 5; k++) {
                                a[i][j][k] = k+j;
                        }
                }
        }

        for(i = 0; i < 2; i++) {
                for(j = 0; j < 5; j++) {
                        b[i][j] = i+j;
                }
        }

        p = &a[0][0][0];
        for(index = 0; index < sizeof(a); index++) {
                printf("index a: %2d; element: %2d\n", index, *(p + index));
        }
        p = &b[0][0];
        for(index = 0; index < sizeof(b); index++) {
                printf("index b: %2d; element: %2d\n", index, *(p + index));
        }
        return 0;
}
8<-----------------------------------------------------------

Compiled with both gcc and g++, this shows a to be two copies of b
arranged contiguously in memory, which would suggest that you can
indeed use memcpy the way you outlined . . .

Looking at my copy of K&R I think that's funamentally how C handles
multidimensional arrays: from the right, each successive subscript
declares an array of n times the size of the array declared so far,
and when accessing an element, each subscript is multiplied by the
size of the array to the right of it and then added to the index
into the area of memory . . . Which isn't very coherent. The perils
of posting well past one's bedtime ;-) Still, I think it's
definitely safe to use memcpy this way . . .

So, memcpy away ;-)

Simon

-- 
PGP public key Id 0x144A991C, or ftp://bg77.anu.edu.au/pub/himi/himi.asc
(crappy) Homepage: http://bg77.anu.edu.au
doe #237 (see http://www.lemuria.org/DeCSS) 
My DeCSS mirror: ftp://bg77.anu.edu.au/pub/mirrors/css/ 

Attachment: msg04826/pgp00000.pgp
Description: PGP signature

Reply via email to