Arrays... what's going on?

closed account (zybCM4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using std::cout;
using std:endl;

int main()
{
   short int numbers[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

   cout << sizeof(numbers) << endl;

   return 0;
}
20


Now according to the reference[1] sizeof() is supposed to get the number of elements in the array. So... since I've explicitly identified that I have ten elements... why is it returning 20?


1. http://www.cplusplus.com/reference/array/array/size/
closed account (zybCM4Gy)
... somehow I think the reference book needs rewriting -_-;; Turns out sizeof gets the bites rather than the items in the array.
sizeof returns the size of the array in bytes.
 
cout << 10 * sizeof(short int) << endl;


The reference page you have been looking at is for the size member function of the std::array class.
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <array>

int main()
{
	std::array<short int, 10> numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

	std::cout << numbers.size() << std::endl;
}

Last edited on
Topic archived. No new replies allowed.