C语言 指向结构变量的指针的大小是多少?



我在这两种情况下都尝试打印指针的大小。对于这两种情况,我都得到8 16作为输出。

#include <stdio.h>
struct Book
{
char name[10];
int price;
};
int main(void)
{
struct Book a;      // Single structure variable
struct Book* ptr;   // Pointer of Structure type
ptr = &a;
struct Book b[10];  // Array of structure variables
struct Book* p;     // Pointer of Structure type
p = &b;
printf("%ld %ldn",sizeof(ptr),sizeof(*ptr));
printf("%ld %ldn",sizeof(p),sizeof(*p));
return 0;
}

首先,sizeof运算符生成一个类型size_t,您必须使用%zu来打印它。

然后,通常在任何体系结构中,指针的大小始终是恒定的,无论它们指向哪种类型。换句话说,指针需要保存内存位置,对于任何正常体系结构,(内存位置的(地址具有固定大小。因此,任何指针的大小都是相同的。

在第二种情况下,这是你想要的吗:

printf("%zu %zun", sizeof(p1), sizeof(*p1));
// Output
8 160

好!让我们从头开始。

正如Sourav Ghosh在他的回答中所说,"pointer需要保存内存位置,对于任何正常的架构,(内存位置的(地址具有固定的大小。因此,任何指针的大小都是相同的",无论它指向的数据类型如何。

现在来到你的问题,考虑并尝试理解你的程序的这个修改版本:

#include <stdio.h>
struct Book
{
char name[10];
int price;
};
int main(void)
{
struct Book b[10];  // Array of structure variables
struct Book* p;     // Pointer to type struct Book
struct Book (*p1)[10]; // Pointer to type struct Book[], which is array of type struct Book
p = b; // same as p = &b[0] but not as p = &b
p1 = &b; // this is how assignment of a pointer to array is done
printf("%zu %zun", sizeof(struct Book*), sizeof(struct Book));
printf("%zu %zun",sizeof(p),sizeof(*p));
printf("%zu %zun",sizeof(p1),sizeof(*p1));
return 0;
}

输出:

// perhaps on your PC
8 16
8 16
8 160
// on my PC
4 16
4 16
4 160

您可以在输出中看到sizeof(struct Book), sizeof(p), and sizeof(p1),都是一样的。因此,任何类型的指针的大小都是相同的。

但是当你打印struct Book的大小时,即你问编译器,"告诉我这个结构书包含多少字节的内存">

对于前两种情况(sizeof(struct Book) or sizeof(*p)),它是 16,对于最后一种情况,它是 160,大小为 10 个类型struct Book的变量。

如果你想知道为什么16作为stuct Book型变量的大小,那是因为charint成员之间的2 padding bytes

阅读这个关于在结构中填充和包装的 SO 问题。

最新更新