Saturday, 30 May 2015

size of Array Vs No of elements in Array

If we wanted to determine the size of array.. the first thought we get is use of sizeof operator.

for the beginner level the size of array means number of elements in array.. which is a false assumptions.

Normally there is so much difference between size of array and number of elements in the array.
lets look at the arduino reference about size of


sizeof :
Description
The sizeof operator returns the number of bytes in a variable type, or the number of bytes occupied by an array.
Syntax
sizeof(variable)
Parameters
variable: any variable type or array (e.g. int, float, byte)
As it says it returns the number of Bytes Occupied by an Array in the Memory 

lets try simple code:

int ex_array[ ] = {1,2}; //define array
int ex_array_length = sizeof(ex_array);//find length using sizeof
void setup(){
Serial.begin(9600);
Serial.print("the value sizeof returns is ");
Serial.println(ex_array_length);
}

void loop(){
//do nothing 
}

The Output is :
the value sizeof return is 4

But the ex_array is having only two elements and the program returns 4.
It means that the array named ex_array[ ] occupied 4 bytes of memory. since int is 16 bits which is equivalent to 2 bytes and two integer variables occupy 4 bytes of memory.

To find the No of elements in Array:
To find number of elements in that array we need to divide the value sizeof returns by sizeof datatype of that array.

so No of elements in array = sizeof(array)/sizeof(datatype of array)


int ex_array[ ] = {1,2}; //define array
int ex_array_elements = sizeof(ex_array)/sizeof(int);//find length using sizeof
void setup(){
Serial.begin(9600);
Serial.print("the number of elements in array is ");
Serial.println(ex_array_elements);
}

void loop(){
//do nothing 
}

The Output is:
the number of elements in array is 2

which solves our present problem...

But if we accidently changed the datatype of array there will be nasty bug if we didn't change the bottom datatype also..

so to avoid that problem we can we something like this
No of elements in array = sizeof(array)/sizeof(first number in array)

int ex_array[ ] = {1,2}; //define array
int ex_array_elements = sizeof(ex_array)/sizeof(ex_arry[0]);//find length using sizeof
void setup(){
Serial.begin(9600);
Serial.print("the number of elements in array is ");
Serial.println(ex_array_elements);
}

void loop(){
//do nothing 
}




No comments:

Post a Comment