Saurav Sahu
Saurav Sahu

Reputation: 13994

Calculation of Array size using sizeof()

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?

Upvotes: 1

Views: 165

Answers (3)

Jitendra
Jitendra

Reputation: 11

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.

Upvotes: 0

Dietmar Kühl
Dietmar Kühl

Reputation: 154045

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.

Upvotes: 4

Scott Hunter
Scott Hunter

Reputation: 49920

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.

Upvotes: 4

Related Questions