Length of array without sizeof
Looping through the array is one of the simplest method to get the length of an array. The implementation could be:
#include<stdio.h>
#include<stdint.h>
void main(void){
uint32_t i =0;
uint32_t? Array[] = {1,2,3,4,5,6,7};
/** First Method by using sizeof operators**/
for( i =0 ; i< (sizeof(Array)/sizeof(Array[0]));i++);
printf("The Lenght of Array is:\t\t%d\n\n",i);
}
The Result will be 7 as the number of elements are 7. But what if our array is 100 element? 200 elements? 300 ....1000.... ?? It's not logical to loop through the array to just only get the length.
>>>>>>>>Here is the solution: The magic of pointers <<<<<<<<
The pointer is a variable that has a fixed size depending on architecture. The type of pointer determine the ability of your pointer to access a location. For example, uint32_t* ptr can access 4 bytes at each time but uint8_t access 1 byte by byte. Let's go in depth with our array:
the array name is an alias to the address of first element with the type of an array element. so, Array is the address of first element with uint32_t type. and so on , ( Array + 1 ) is the address of the second element.
But &Array is an alias to the address of the same Array address but with a size of the all of element array so (&Array + 1 ) will point the address after the all size of array with >> with different type from Array + 1 <<.
But what do you think if we dereference the ( &Array + 1) like that :
领英推è
*( &Array + 1) ? Of course now we point at the same address but with the same type as Array + 1.
This mean that we can do subtraction on the two pointers which will refer to the length of array (the number of step between the two addresses).
#include<stdio.h>
#include<stdint.h>
void main(void)
{
uint32_t i =0;
uint32_t? Array[] = {1,2,3,4,5,6,7};
/** First Method by using sizeof operators**/
for( i =0 ; i< (sizeof(Array)/sizeof(Array[0]));i++);
printf("The Lenght of Array is:%d\n",i);
/** Second Method by using Pointers**/
printf("The Lenght of Array is:%d\n",*(&Array+1)-(Array));
}
by this way , however the number of element , you will get the length easily
#embeddedsystems #embeddedc #embeddedengineer #embeddedsoftware #embedded #embeddedprogramming #embeddeddevelopment #pointers #array #cprogramming