MCG MCG - 1 year ago 63
C Question

Size of multi dimentional array

I was trying to get the size of the 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 prints, I am getting size equal to 4. Can someone explain how does sizeof work in case multi-dimensional array? Why output is same in 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