#include <stdio.h>
int main()
{
int (*ptr) [5];
printf ("%lu\n" , sizeof (ptr));
printf ("%lu\n" , sizeof (*ptr));
}
我使用的是64位系统.当我在GCC编译器中运行这段代码时,它会生成输出8 and 20
.我的问题是,要为这pointer to an array
分配多少字节?现在是8点还是20点,为什么?
#include <stdio.h>
int main()
{
int (*ptr) [5];
printf ("%lu\n" , sizeof (ptr));
printf ("%lu\n" , sizeof (*ptr));
}
我使用的是64位系统.当我在GCC编译器中运行这段代码时,它会生成输出8 and 20
.我的问题是,要为这pointer to an array
分配多少字节?现在是8点还是20点,为什么?
ptr
指定将存储int
的5元素数组中的address的对象.在您的系统上,这样的指针占用8字节的存储空间.
expression *ptr
可以指定一个由5个元素组成的int
数组的对象;在您的系统上,这样的数组占用20个字节(5个4字节元素).
假设代码:
int (*ptr)[5] = malloc( sizeof *ptr );
这将为您提供类似以下内容的内容(每个框占用4个字节):
+---+ +---+
ptr: | | -----> | | (*ptr)[0] // we don't want to index into ptr,
+ - + +---+ // we want to index into what ptr
| | | | (*ptr)[1] // *points to*, hence the explicit
+---+ +---+ // dereference on ptr.
| | (*ptr)[2] //
+---+ // Since a[i] is defined as *(a + i),
| | (*ptr)[3] // (*ptr)[i] == (*(ptr + 0))[i] ==
+---+ // (ptr[0])[i] == ptr[0][i]
| | (*ptr)[4] //
+---+
sizeof ptr == sizeof (int (*)[5]) == 8 // assuming 8-byte addresses
sizeof *ptr == sizeof (int [5]) == 20 // assuming 4-byte int
这相当于写
int arr[5]; // sizeof arr == sizeof (int [5]) == 20
int (*ptr)[5] = &arr; // sizeof ptr == sizeof (int (*)[5]) == 8
指针的大小并不取决于它所指向的对象的大小.