简体   繁体   English

解引用指向结构变量的指针

[英]Dereference Pointer to Struct Variable

I try to understand what value we get when dereference the pointer to struct.我试图了解在取消引用指向结构的指针时我们得到了什么值。

My struct is.我的结构是。

    struct car
{
    int a = 5;
    int b = 10;
    int c = 2;
    int d = 14;
    int e = 20;
};

My code in main function is我在主函数中的代码是

int main()
{
    car  k1,k2,k3,k4,k5; // declare struct variable
    car* ptr1,*ptr2,*ptr3,*ptr4,*ptr5;// declare pointer to struct variable
    ptr1 = &k1;
    ptr2 = &k2;
    ptr3 = &k3;
    ptr4 = &k4;
    ptr5 = &k5;

    printf("*ptr1=%d *ptr2=%d *ptr3=%d *ptr4=%d *ptr5=%d  \n", *ptr1,*ptr2,*ptr3,*ptr4,*ptr5);
 };

When I dereference ptr1 to ptr5.I get the value correspond with the value of member in struct(value a to e).Why I get this value.当我将 ptr1 取消引用到 ptr5 时。我得到的值与结构中成员的值相对应(值 a 到 e)。为什么我得到这个值。

To be able to print struct you need to overload operator << .为了能够打印结构,您需要重载operator << Your struct then should look like this:你的结构应该是这样的:

struct car
{
    int a = 5;
    int b = 10;
    int c = 2;
    int d = 14;
    int e = 20;

    friend std::ostream& operator<<(std::ostream& os, const car& c) {
      os << "Struct data:\n";
      os << "------------\n";
      os << "a var: " + std::to_string(c.a) + "\n";
      os << "b var: " + std::to_string(c.b) + "\n";
      os << "c var: " + std::to_string(c.b) + "\n";
      os << "d var: " + std::to_string(c.b) + "\n";
      os << "e var: " + std::to_string(c.b) + "\n";
      return os;
    }
};

Then if you would print dereferenced ptr like this:然后,如果您像这样打印取消引用的 ptr:

std::cout << *ptr1 << std::endl;

You will see output like this:你会看到这样的输出:

Struct data:
------------
a var: 5
b var: 10
c var: 10
d var: 10
e var: 10

You can return what you want, depends on you.您可以返回您想要的东西,这取决于您。

Variadic functions do not have type checking and practically may pun types.可变函数没有类型检查,实际上可能是双关类型。 Essentially you passed content of structure as raw values and format string described how to treat them.本质上,您将结构内容作为原始值传递,格式字符串描述了如何处理它们。 Luckily, in this case struct has no padding, so first five integers were read accordingly.幸运的是,在这种情况下 struct 没有填充,因此相应地读取了前五个整数。 The behaviour in this case is unspecified and depends on implementation of compiler and ABI.这种情况下的行为是未指定的,取决于编译器和 ABI 的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM