为什么sizeof(* node)给出结构的大小而不是指针的大小

时间:2014-09-12 12:21:12

标签: c++ c pointers sizeof

在下面的代码中:

typedef struct{int data1; int data2} node;
node n1;
node* n2;

sizeof(n1) returns 8 // size of the struct node
sizeof(n2) returns 4 // since n2 is a pointer it returns the size of the pointer
sizeof(*n2) returns 8 // HOW DOES THIS WORK ?

sizeof实际上如何运作?在上面的例子中,* n2归结为提供n2指向的地址。在这种情况下,n2仍然是一个悬空指针,因为我们既没有分配内存,也没有将它指向某个有效地址。它如何正确地给出结构的大小?

3 个答案:

答案 0 :(得分:13)

你需要了解两件事:

首先,*n2的类型是什么? n2的类型是指向node的指针,因此*n2的类型为node

其次,你是对的n2是一个悬空指针,它没有指向一个有效的位置,但是sizeof的魔力是,它是一个编译时运算符(当操作数是C99可变长度数组时除外),sizeof(*n2)在编译时被评估为与sizeof(node)相同。

答案 1 :(得分:2)

基本上,您可以将*n2视为“n2指向​​的东西”。

n2指向的是一个节点,节点的大小是8.简单就是...... 它是否已被分配并不重要:n2所指向的东西的类型是节点,节点的大小是8。

答案 2 :(得分:1)

执行*n2n2定义为node* n2,您基本上是在告诉读取地址 n2的数据好像它有类型node

在该地址上写的内容并不重要。考虑将这些行添加到您的示例中:

void *n3 = n2; // copies the address, but no information about the data there
int *n4 = (int *)n3; // again, copies the address

sizeof(*n4) returns sizeof(int)

所以基本上,总结一下,如果你有:

X* a;
sizeof(a); // will always return 4, the size of a pointer
sizeof(*a); // will always return sizeof(X), no matter if the address is set.
相关问题