Michael McKinney
Michael McKinney

Reputation: 45

c++ sizeof - need help understanding

I am having trouble understanding a line of code. I see that an array is initialized as follows:

static const uint SmartBatteryWattHoursTable[1 << 4] = {
  0,  14,  27,  41,  54,  68,  86, 104,
120, 150, 180, 210, 240, 270, 300, 330};

However I can't tell what the following code means:

int x  = sizeof(SmartBatteryWattHoursTable) / sizeof(*SmartBatteryWattHoursTable));

I understand that the numerator will evaluate to 16 * 4 = 64. But what does the denominator evaluate to?

Upvotes: 1

Views: 98

Answers (2)

eerorika
eerorika

Reputation: 238461

But what does the denominator evaluate to?

sizeof(*SmartBatteryWattHoursTable) evaluates to the size of the type of the expression *SmartBatteryWattHoursTable. The type of that expression is the same as the element of the array, which is uint.

In other words, sizeof(SmartBatteryWattHoursTable) / sizeof(*SmartBatteryWattHoursTable)) is a way to calculate the size of the array in number of elements (as opposed to the size in number of bytes that the numerator is).

A simpler way to write this is std::size(SmartBatteryWattHoursTable).

Upvotes: 7

Remy Lebeau
Remy Lebeau

Reputation: 598319

The code is declaring an array of 16 (1 << 4) uint values.

The statement sizeof(SmartBatteryWattHoursTable) returns the byte size of the entire array, thus sizeof(uint) * 16 = 64 (assuming a 4-byte uint).

An array decays into a pointer to the 1st element, thus *SmartBatteryWattHoursTable is the same as *(&SmartBatteryWattHoursTable[0]). So the statement sizeof(*SmartBatteryWattHoursTable) returns the byte size of the 1st element of the array, ie of a single uint, thus 4.

Thus, x is set to 64 / 4 = 16, ie the number of elements in the array.

This is a very common way to get the element size of a fixed array, prior to the addition of std::size() to the standard C++ library in C++17 (and std::ssize() in C++20).

Upvotes: 4

Related Questions