取消引用结构以获得第一个成员的价值 [英] Dereference a structure to get value of first member

查看:189
本文介绍了取消引用结构以获得第一个成员的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现结构的第一个元素的地址与结构的地址相同。但是,取消引用结构的地址不会返回第一个数据成员的值。但是,取消引用第一个数据成员的地址的确会返回其值。例如。结构的地址= 100,结构的第一个元素的地址也为100。现在,解除引用应该在两者上以相同的方式进行。

I found out that address of first element of structure is same as the address of structure. But dereferencing address of structure doesn't return me value of first data member. However dereferencing address of first data member does return it's value. eg. Address of structure=100, address of first element of structure is also 100. Now dereferencing should work in the same way on both.

代码:

#include <iostream>
#include <cstring>

struct things{
    int good;
    int bad;
};

int main()
{
    things *ptr = new things;
    ptr->bad = 3;
    ptr->good = 7;
    std::cout << *(&(ptr->good)) <<" " << &(ptr->good) << std::endl;
    std::cout << "ptr also print same address = " << ptr << std::endl;
    std::cout << "But *ptr does not print 7 and gives compile time error. Why ?" << *ptr << std::endl;
    return 0;
}


推荐答案

尝试任何这些

#include <iostream>
#include <cstring>

struct things{
    int good;
    int bad;
};

int main()
{
    things *ptr = new things;
    ptr->bad = 3;
    ptr->good = 7;

    std::cout <<  *(int*)ptr << std::endl;
    std::cout <<  *reinterpret_cast<int*>(ptr) << std::endl;

    int* p = reinterpret_cast<int*>(ptr);
    std::cout <<  *p << std::endl;
    return 0;
}

这篇关于取消引用结构以获得第一个成员的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆