AC wrote:
I noticed that if I declared an array a as
int a[2][3][1], sizeof a is 6 * sizeof(int).
This means that a occupies 6*sizeof(int) consecutive bytes, right?
So I can consider, (int *) &a as a pointer to an array of 2*3*1=6
ints. Is this correct?
This code works fine for me :
#include <stdio.h>
int
main(void)
{
int a[2][3][1]={1,2,3,4,5,6};
int *p;
int i;
printf("sizeof a =%u\n",(unsigned int) sizeof a);
p = (int *) &a;
for(i=0; i < sizeof a/sizeof(int);i++)
printf("p[%d]=%d\n",i,p[i]);
return 0;
}
Looks fine to me. You might want to try this modification, playing
with the various *DIM defines, to see the correspondence of the
linear array and the multidimensional array. C only has a single
array dimension, and multidimensional arrays simply are a mapping
into a single dimensional array. Notice How I have intermixed
array and pointer notation.
Keep the dimensions below 10 so the displays show all coordinates.
#include <stdio.h>
#define XDIM 4
#define YDIM 3
#define ZDIM 2
#define LINEMAX 72
void dump(int a[][YDIM][ZDIM], size_t sz)
{
int linesize;
size_t ix;
int *p;
p = (int *)a;
linesize = 0;
for (linesize = 0, ix = 0; ix < sz; ix++) {
linesize += printf("p[%2d]=%0.3d", (int)ix, p[ix]);
if (linesize <= LINEMAX) {
putchar(' '); linesize++;
}
else {
putchar('\n'); linesize = 0;
}
}
if (linesize) putchar('\n');
} /* dump */
/* -------------------- */
void inita(int a[][YDIM][ZDIM])
{
int x, y, z;
size_t ix;
int *p;
p = (int *)&a;
for (x = 0; x < XDIM; x++)
for (y = 0; y < YDIM; y++)
for (z = 0; z < ZDIM; z++) {
ix = (((z * ZDIM) + y) * YDIM) + x;
a[x][y][z] = ((z * 10 + y) * 10) + x;
}
} /* inita */
/* -------------------- */
int main(void)
{
int a[XDIM][YDIM][ZDIM] = {1,2,3,4,5,6};
int *p;
size_t ix;
printf("sizeof a = %lu\n", (unsigned long) sizeof a);
p = (int *) &a;
for (ix = 0; ix < sizeof a/sizeof(int); ix++)
printf("p[%d]=%d\n", (int)ix, p[ix]);
dump(a, sizeof a/sizeof(int));
inita(a);
dump(a, sizeof a/sizeof(int));
return 0;
}
--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson