为什么在 sizeof() 函数中与 * 运算符一起使用和不使用 * 运算符时,指向结构变量的指针大小会有所不同?
Why is there a difference in the size of pointer to the struct variable when used with and without * operator in the sizeof() function?
using namespace std;
#include<iostream>
int main()
{
struct node
{
int data;
struct node *next;
};
struct node *node1;
node1 = (struct node*)malloc(sizeof(node));
node1->data = 5;
node1->next = NULL;
cout<<"node data value "<<node1->data<<endl;
int *vara;
cout<<"size of struct node pointer with * "<<sizeof(*node1)<<endl; // size is 8
cout<<"size of struct node pointer without * "<<sizeof(node1)<<endl; // size is 4
cout<<"size of integer pointer variable with * "<<sizeof(*vara)<<endl; // size is 4
cout<<"size of integer pointer variable with * "<<sizeof(*vara)<<endl; // size is 4 in this case as well
}
为什么与*
运算符一起使用时*
与指向结构变量的指针一起使用时大小会有所不同?
在代码块,语言C++中执行了上述代码。
简短的回答:因为node1
是一个指针,*node1
是一个node
,而且它们有不同的大小。
更长的答案:
让我们检查一下传递给sizeof
运算符的每个表达式的类型:
*node1
有类型node
,它由一个int
和一个node*
组成,它们在您的平台上都有 4 个字节的大小,因此总大小为 8 字节。node1
有类型node*
,这是一个指针。在您的平台上,指针的长度为 4 个字节。*vara
的类型为int
,它是一个整数。在您的平台上,整数的长度为 4 个字节。vara
有类型int*
,这是一个指针。在您的平台上,指针的长度为 4 个字节。
第一个sizeof
返回结构的大小(int
的大小 + 指针的大小),第二个返回指向结构的指针的大小(计算机上为 4 个字节),第三个返回整数的大小。
为什么当
与指向结构变量的指针一起使用时,与"运算符一起使用时,大小会有所不同?
因为它们是不同的类型。在本声明中:
node *ptr;
ptr
有类型pointer to node
,而*ptr
有类型node
。在您的第三个和第四个示例中,您似乎想比较int
与int *
.您获得相同大小的int *
和int
只是一个巧合,并且恰好在您的平台上是相同的。你既不能依赖它,也不能从这个事实中推断出任何规则。
这是因为在这种情况下,指针的大小(4 个字节)与整数相同,但node
结构的大小为 8 个字节。 当您在a
是指针时请求sizeof(a)
时,您要求指针的大小。当你要求sizeof(*a)
时,你要求a
所指的大小。
相关文章:
- 函数参数变量总是需要 & 或 * 运算符吗?
- 在未初始化的变量上使用复合赋值运算符(+=, ..)不是C++中的UB?
- 如何正确返回带有成员变量的重载运算符++?
- 如何在不使用赋值运算符的情况下为动态变量赋值?
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 变量地址的运算符[]是如何工作的
- 在C++中,为什么int可以使用new运算符初始化变量,而double不能
- 创建变量之间的运算符排列
- C++中重载复合赋值运算符不会更改变量
- 为什么通过通用引用运算符 (&&) 将变量的引用传递给 Varadic 模板函数失败?
- 为什么 ++ 运算符触发器返回对局部变量警告的引用
- 使用运算符将分隔的输入分隔>>变量
- 不太明白 & 运算符的地址在这个结构中做什么,以及它如何能够访问其他成员变量
- 为什么在 sizeof() 函数中与 * 运算符一起使用和不使用 * 运算符时,指向结构变量的指针大小会有所不同?
- 隐藏的成员变量不应在仅允许const访问的基类中突变,以便保留分配运算符
- 将删除运算符放置在何处以进行动态变量
- 重载运算符和静态成员变量的行为
- 为什么我的重载运算符+在向自身添加变量时会在返回时使"this"未初始化?
- 需要使用 Book* 头变量重载运算符,但不起作用
- 三元运算符:编译器不发出局部变量警告的返回引用