If you know the data type of the array, you can use something like:
int arr[] = {23, 12, 423, 43, 21, 43, 65, 76, 22};
int noofele = sizeof(arr)/sizeof(int);
Or if you don't know the data type of array, you can use something like:
noofele = sizeof(arr)/sizeof(arr[0]);
Note: This thing only works if the array is not defined at run time (like malloc) and the array is not passed in a function. In both cases, arr (array name) is a pointer.
It is worth noting that sizeof doesn't help when dealing with an array value that has decayed to a pointer: even though it points to the start of an array, to the compiler it is the same as a pointer to a single element of that array. A pointer does not "remember" anything else about the array that was used to initialize it.
int a[10];
int* p = a;
assert(sizeof(a) / sizeof(a[0]) == 10);
assert(sizeof(p) == sizeof(int*));
assert(sizeof(*p) == sizeof(int));
If you know the data type of the array, you can use something like:
Or if you don't know the data type of array, you can use something like:
Note: This thing only works if the array is not defined at run time (like malloc) and the array is not passed in a function. In both cases,
arr
(array name) is a pointer.For multidimensional arrays it is a tad more complicated. Oftenly people define explicit macro constants, i.e.
But these constants can be evaluated at compile-time too with sizeof:
Note that this code works in C and C++. For arrays with more than two dimensions use
etc., ad infinitum.
You can use the
&
operator. Here is the source code:Here is the sample output
It is worth noting that
sizeof
doesn't help when dealing with an array value that has decayed to a pointer: even though it points to the start of an array, to the compiler it is the same as a pointer to a single element of that array. A pointer does not "remember" anything else about the array that was used to initialize it.for more details: https://aticleworld.com/how-to-find-sizeof-array-in-cc-without-using-sizeof/ https://www.geeksforgeeks.org/how-to-find-size-of-array-in-cc-without-using-sizeof-operator/