为什么 int 指针的大小与 int 数组的大小不同?
Why size of int pointer is different of size of int array?
让我们编写以下代码:
int x;
int *p = &x;
int t[3];
然后sizeof returns:
sizeof(x) -> 4
sizeof(p) -> 8
sizeof(t) -> 12
我想 sizeof(t)
是 3 * sizeof(int)
的结果。
但是由于 t
是指向他第一个元素的指针,所以它的大小应该是 sizeof(p)
.
为什么sizeof(t)
returns代表数组的内存块的大小?
谢谢。
t
是int[3]
类型,不是指针类型。
所以它的大小是3 * sizeof(int)
。
在某些情况下,t
衰减到一个指针,但这不是其中之一。
因为变量t
被声明为数组类型
int t[3];
然后 sizeof( t )
产生一个等于 3 * sizeof( int )
的值
C 标准(6.5.3.4 sizeof 和 alignof 运算符)
2 The sizeof operator yields the size (in bytes) of its operand,
实际上,具有三个 int
类型元素的数组占用的内存等于 3 * sizeof( int )
.
在表达式中,很少有例外,如在 sizeof
运算符中使用,数组指示符被转换为指向其第一个元素的指针。
因此,如果您将使用例如以下表达式
sizeof( t + 0 )
然后表达式 t + 0
中的 t
将被转换为指针,您将得到 sizeof( t + 0 )
等于指向 int
的指针的大小平台,即 8
.
来自 C 标准(6.3.2.1 左值、数组和函数指示符)
3 Except when it is the operand of the sizeof operator or the unary &
operator, or is a string literal used to initialize an array, an
expression that has type ‘‘array of type’’ is converted to an
expression with type ‘‘pointer to type’’ that points to the initial
element of the array object and is not an lvalue. If the array object
has register storage class, the behavior is undefined.
让我们编写以下代码:
int x;
int *p = &x;
int t[3];
然后sizeof returns:
sizeof(x) -> 4
sizeof(p) -> 8
sizeof(t) -> 12
我想 sizeof(t)
是 3 * sizeof(int)
的结果。
但是由于 t
是指向他第一个元素的指针,所以它的大小应该是 sizeof(p)
.
为什么sizeof(t)
returns代表数组的内存块的大小?
谢谢。
t
是int[3]
类型,不是指针类型。
所以它的大小是3 * sizeof(int)
。
在某些情况下,t
衰减到一个指针,但这不是其中之一。
因为变量t
被声明为数组类型
int t[3];
然后 sizeof( t )
产生一个等于 3 * sizeof( int )
C 标准(6.5.3.4 sizeof 和 alignof 运算符)
2 The sizeof operator yields the size (in bytes) of its operand,
实际上,具有三个 int
类型元素的数组占用的内存等于 3 * sizeof( int )
.
在表达式中,很少有例外,如在 sizeof
运算符中使用,数组指示符被转换为指向其第一个元素的指针。
因此,如果您将使用例如以下表达式
sizeof( t + 0 )
然后表达式 t + 0
中的 t
将被转换为指针,您将得到 sizeof( t + 0 )
等于指向 int
的指针的大小平台,即 8
.
来自 C 标准(6.3.2.1 左值、数组和函数指示符)
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.