MCG MCG - 4 years ago 104
C Question

Size of multi dimensional array

I was trying to get the size of a multidimensional array and wrote code in C as shown below.

#include <stdio.h>

char b[3][4];

int main(void){
printf("Size of array b[3]=%d\n", sizeof(b[3]));
printf("Size of array b[2]=%d\n", sizeof(b[2]));
printf("Size of array b[5]=%d\n", sizeof(b[5]));

return 0;

In all above three print statements, I am getting size equal to 4. Can someone explain how
works in case of a multi-dimensional array? Why is the output the same in the third print?

Answer Source

b is a 2D character array of rows 3 and columns 4.

So, if you take sizeof(b) you will get 12.

b[0] (and b[i] in general) has a type of a 1D character array of size 4. So. if you take sizeof (b[0]) you will get 4.

b[0][0] (and b[i][j] in general) has a type of char. So if you take sizeof (b[0][0]) you will get 1.

sizeof does not depend on the array index. The type remains the same even for b[0] and b[100], even though it might be out of range of the memory of the array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download