Calculation of Array size using sizeof()

212 Views Asked by At

Excerpt from TopCoder article:

The expression sizeof(data)/sizeof(data[0]) returns the size of the array data, but only in a few cases, so don’t use it anywhere except in such constructions.(C programmers will agree with me!)

To get array size, I've been using this expression sizeof(data)/sizeof(data[0]) all the time for all primitive types.

Does anyone know about any such case in which the above expression should not be used?

3

There are 3 best solutions below

0
Scott Hunter On BEST ANSWER

If data were declared like so:

int *data;

And then space for it allocated like so:

data = malloc( NUM_ELEMENTS * sizeof(int) );

Then your technique will not work, because sizeof(data) is the size of a pointer, not the content of the array.

5
Dietmar Kühl On

The sizeof approach compiles but doesn't work when giving it a pointer or an array of indeterminate size. Just use the proper C++ approach:

template <typename T, std::size_t N>
constexpr std::size_t size(T(&)[N]) {
    return N;
}

Using size() on an array works correctly. It will be a compile-time error to use it in a case where it is not applicable, e.g., on a pointer.

0
Jitendra On

The sizeof technique work correction for static array, it will not have any issue. As mentioned in the above for dynamic array and pointer data it will not work correctly.