How does this C code generate the correct size for the first index of a multi-dimesional array

StackOverflow https://stackoverflow.com/questions/21388827

  •  03-10-2022
  •  | 
  •  

Question

In reviewing C, I was looking at "Thinking in C:Foundations for Java and C++", http://www.mindview.com

I modified an example of three dimensional arrays to the code below. The original code has a magic number of 2 for the outer loop terminator.

/* Illustrates a multi-dim array */
#include <stdio.h>
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))

int main(void)
{
    int a[][3][2] = {{{1,2}, {3,4}, {5,6}},
                     {{7,8}, {9,0}, {1,2}}};
    int i, j, k;
    printf("sizeof a=%d,sizeof a[0]=%d\n",sizeof(a),sizeof(a[0]));

    for (i = 0; i < ARRAY_SIZE(a); ++i) {
        for (j = 0; j < 3; ++j) {
            for (k = 0; k < 2; ++k)
                printf("%d ", a[i][j][k]);
            putchar('\n');
        }
        putchar('\n');
    }
    return 0;
}

The output is

sizeof a=48,sizeof a[0]=24
1 2 
3 4 
5 6 

7 8 
9 0 
1 2 

sizeof(a) is 48. Understandable 2*3*2*4=6*8=48. The ARRAY_SIZE macro returns the correct value of 2.

My question is how is this determined? How is a re-reference of a[][3][2] to a[0] return a size of 24? What are the C 'rules' that are followed to create this result.

Program built with int=32 bits. I'm using GNU GCC 4.6.2 supplied with MinGW.

Was it helpful?

Solution

For this you need to understand what the types of your subarrays are:

*a or a[0] is a type int[3][2] thus sizeof(a[0]) = 6 * sizeof(int) = 24.

**a or a[0][0] is of type int[2]

***a is of type int

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top