How to reliably get size of C-style array?

In C array parameters in C are really just pointers so sizeof() won’t work. You either need to pass in the size as another parameter or use a sentinel – whichever is most appropriate for your design.

Some other options:

Some other info:

  • for C++, instead of passing a raw array pointer, you might want to have the parameter use something that wraps the array in a class template that keeps track of the array size and provides methods to copy data into the array in a safe manner. Something like STLSoft’s array_proxy template or Boost’s boost::array might help. I’ve used an array_proxy template to nice effect before. Inside the function using the parameter, you get std::vector like operations, but the caller of the function can be using a simple C array. There’s no copying of the array – the array_proxy template takes care of packaging the array pointer and the array’s size nearly automatically.

  • a macro to use in C for determining the number of elements in an array (for when sizeof() might help – ie., you’re not dealing with a simple pointer): Is there a standard function in C that would return the length of an array?

Leave a Comment