SAcoder
SAcoder

Reputation: 61

How does C++ find the size of an array?

Difference From Other Questions

I am not asking how to find the size, but how the computer finds the size.

Goal

I want to find out how C++ finds the size of an array (using sizeof(array)), and a 2D array (using sizeof(array)).

When I ran the code, I thought the output would be 3 and 6. But it was 12 and 24!? How do I make the the output 3 and 6?

I don't know how to calculate the size of an array, so when I say "an output of three/six", I mean the amount of numbers in the array.

Code

#include <iostream>
using namespace std;

int main()
{
    int oneDArray [3] = {1, 2, 3};
    int twoDArray [2][3] = {{1, 2, 3}, {1, 2, 3}};

    cout << sizeof(oneDArray) << "\n" << sizeof(twoDArray);

    return 0;
}

Upvotes: 1

Views: 17804

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155704

The sizeof operator returns the size in bytes, not elements.

For single dimensional arrays (not passed as a function argument, which would cause decay to a pointer), you can get the element count by dividing the size of the array by the size of the first element, e.g.

sizeof(oneDArray) / sizeof(oneDArray[0])  // Gets 3

For multidimensional arrays, that would tell you the size of the first dimension, not the number of elements total, so you'd need to drill down deeper:

sizeof(twoDArray) / sizeof(twoDArray[0])  // Gets 2 (first dimension of array)
sizeof(twoDArray) / sizeof(twoDArray[0][0])  // Gets 6 (number of elements)

You can of course explicitly name the type of an element to avoid nested indexing (sizeof(twoDArray) / sizeof(int) get 6 just fine), but I avoid it as a rule; it's too common for an array to change types during development (say, it turns out you need to use int64_t because you have values into the trillions), and if the whole expression isn't in terms of the array, it's easy to overlook it and end up with broken code.

Upvotes: 10

Cory Kramer
Cory Kramer

Reputation: 118021

sizeof returns bytes, if you expect number of elements, divide by the size of each element

cout << sizeof(oneDArray)/sizeof(int) << "\n" << sizeof(twoDArray)/sizeof(int);

Output:

3
6

Upvotes: 6

Related Questions