Mysterious result from sizeof(array[]) in constructor initialization list

In the following example sizeof(ar[0]) is taken twice for the same array.
First in main, where the result is correct.
Then again in the Row class constructor initialization list, where the result is wrong.
What happened?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

class Row
{
	private:
		int *ar;
		int elementSize;
		int arraySize;
	public:
		Row (int ar[]): ar(ar),
			elementSize(sizeof(ar)),
			arraySize(sizeof(ar[0])) {}
		void printSize()
		{
			std::cout << "in Row\tarraySize=" << arraySize	//4 is wrong
				<< " elementSize=" << elementSize
				<< " ar=" << ar[0] << "," << ar[1] << std::endl;
	       	}
};

int main()
{
	int a=8;
	int b=9;
	int ar[] = { a, b };
	int arraySize = sizeof(ar);
	int elementSize = sizeof(ar[0]);
	std::cout << "in main\tarraySize=" << arraySize			//8 is correct
		<< " elementSize=" << elementSize
		<< " ar=" << ar[0] << "," << ar[1] << std::endl;

	Row row(ar);
	row.printSize();
}


output:
in main arraySize=8 elementSize=4 ar=8,9
in Row  arraySize=4 elementSize=4 ar=8,9

Thank you.
Last edited on
> Then again in the Row class constructor

Arrays are not CopyAssignable; Row constructor accepts a pointer to int.
Row( int ar[] ) is the same as Row( int* a ); sizeof(a) == sizeof(pointer to int)

Use std::array<>, perhaps? http://en.cppreference.com/w/cpp/container/array
Thank you again JLBorges.
Topic archived. No new replies allowed.