Sunday, May 25, 2014

Calculate the size of an array at run time

Calculate the size of an array at run time


In c language there is no direct way to calculate the size of an array at run time;

For example:

int array[10] = {1,2,3,4,54,6,7,8,9,3}

To calculate the size of above array at run time:

int size = sizeof(array) / sizeof(array[0]);


sizeof(array) = 20 for 16 bit (2 Byte) compiler
sizeof(array) = 40 for 32 bit (4 Byte) compiler 


sizeof(array[0]) = 2 for 16 bit (2 Byte) compiler
sizeof(array[0]) = 4 for 32 bit (4 Byte) compiler


// For 16 Bit compiler
size = 20 / 2
size = 10
//For 32 Bit Compiler
size = 40 / 4 for 32 Bit
size = 10

What is sizeof() ?

By +Dixit Singla