And I would like to calculate the size of this array so that I can send it on UART port linux using this function...
You need a COUNTOF
macro or function. They can be tricky to get right in all cases. For example, the accepted answer shown below will silently fail when working with pointers:
size_t size = sizeof array;
size_t number_element = sizeof array / sizeof *array;
Microsoft Visual Studio 2005 has a built-in macro or template class called _countof
. It handles all cases properly. Also see the _countof Macro documentation on MSDN.
On non-Microsoft systems, I believe you can use something like the following. It will handle pointers properly (from making COUNTOF suck less):
template <typename T, size_t N>
char (&ArraySizeHelper( T (&arr)[N] ))[N];
#define COUNTOF(arr) ( sizeof(ArraySizeHelper(arr)) )
void foo(int primes[]) {
// compiler error: primes is not an array
std::cout << COUNTOF(primes) << std::endl;
}
Another good reference is Better array 'countof' implementation with C++ 11. It discusses the ways to do things incorrectly, and how to do things correctly under different compilers, like Clang, ICC, GCC and MSVC. It include the Visual Studio trick.
buff is an array which can change size during program execution
As long as you have the data at compile time, the countof
macro or function should work. If you are building data on the fly, then it probably won't work.
This is closely related: Common array length macro for C?. It may even be a duplicate.