[当我声明一个大小为10的整数数组并检查它的大小为40时,但当我声明一个大小为10的数组整数指针变量时,我尝试检查它的大小始终为8。为什么?
int A[10];
cout<<sizeof(A)<<endl; // it gives 40;
int *p;
p = new int[10];
cout<<sizeof(*p)<<endl; // but it gives always 8;
在典型的64位计算机上,sizeof(*p)
应该为4
,而sizeof(p)
应该为8
。
希望这个例子可以解决问题:
int p1[10];
cout<<sizeof(*p1)<<endl; // 4 size of the first element (int)
cout<<sizeof(p1)<<endl; // 40 size of array (int size * 10)
int *p2;
p2 = new int[10];
cout<<sizeof(*p2)<<endl; // 4 size of the first element (int)
cout<<sizeof(p2)<<endl; // 8 size of the pointer on 64-bit system
// shows how you're getting the first value by dereferencing
cout<<*p2<<endl; // 0
p2[0] = 100;
cout<<*p2<<endl; // 100
[sizeof(p)
始终为sizeof(int*)
,在您的平台上为8。
无论您使用new []
分配的对象数量如何,这种情况都不会改变。
A
的类型为int [10]
(10个int
s的数组)。其大小为10 * sizeof(int)
。sizeof(A)
为40是有道理的。
指针和数组是不同的类型。它们可以在许多用例中互换使用,但是了解它们之间的差异以及它们在何处表现不同也很重要。 sizeof
运算符是它们不同的用例之一。
总是指针保存数组的起始地址。由于它是一个int指针,并且在您的系统中int的大小为8个字节,因此它显示为8个字节。