![](/img/trans.png)
[英]Why does sizeof(argv)/sizeof(argv[0]) give me the size of an array in C++?
[英]Why does sizeof(*node) give the size of the structure and not size of the pointer
在以下代码中:
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仍然是一个悬空指针,因为我们既没有分配内存,也没有将它指向某个有效地址。 它如何正确地给出结构的大小?
你需要了解两件事:
首先, *n2
的类型是什么? n2
的类型是指向node
的指针,因此*n2
的类型是node
。
第二,你是对的n2
是一个悬空指针,它没有指向一个有效的位置,但sizeof
的魔力是,它是一个编译时运算符 (当操作数是C99可变长度数组时除外), sizeof(*n2)
在编译时被评估为与sizeof(node)
相同。
基本上,您可以将*n2
读作“n2指向的东西”。
n2所指向的是一个节点,一个节点的大小是8.简单就是......它是否被分配无关紧要:n2所指向的东西的类型是一个节点,节点的大小为8。
当你执行*n2
,其中n2
被定义为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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.