为什么在 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?

本文关键字:运算符 变量 结构 有所不同 指针 sizeof 函数 为什么 一起      更新时间:2023-10-16
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运算符的每个表达式的类型:

  1. *node1有类型node,它由一个int和一个node*组成,它们在您的平台上都有 4 个字节的大小,因此总大小为 8 字节。
  2. node1有类型node*这是一个指针。在您的平台上,指针的长度为 4 个字节。
  3. *vara的类型为int它是一个整数。在您的平台上,整数的长度为 4 个字节。
  4. vara有类型int*这是一个指针。在您的平台上,指针的长度为 4 个字节。

第一个sizeof返回结构的大小(int的大小 + 指针的大小),第二个返回指向结构的指针的大小(计算机上为 4 个字节),第三个返回整数的大小。

为什么当

与指向结构变量的指针一起使用时,与"运算符一起使用时,大小会有所不同?

因为它们是不同的类型。在本声明中:

node *ptr;

ptr有类型pointer to node,而*ptr有类型node。在您的第三个和第四个示例中,您似乎想比较intint *.您获得相同大小的int *int只是一个巧合,并且恰好在您的平台上是相同的。你既不能依赖它,也不能从这个事实中推断出任何规则。

这是因为在这种情况下,指针的大小(4 个字节)与整数相同,但node结构的大小为 8 个字节。 当您在a是指针时请求sizeof(a)时,您要求指针的大小。当你要求sizeof(*a)时,你要求a所指的大小。

相关文章: