gpt4 book ai didi

c++ - 使用内存地址访问结构的属性值

转载 作者:搜寻专家 更新时间:2023-10-31 02:04:50 26 4
gpt4 key购买 nike

我正在尝试使用 C++ 中的指针来提高我的知识,并且我想通过内存地址访问结构的属性值。我定义了这个结构:

#pragma once
typedef struct EXAMPLE_STRUCT{
uint8_t a;
uint16_t b;
float c;
} Example_Struct;

我想使用内存地址(不是属性名称)获取 a 的值:

Example_Struct* ptr;
ptr = &(wheather_struct[0]);

此刻,我在 ptr 中有结构中第一个元素的内存地址值。所以,我认为这是 a 变量的内存地址。然后我试图像这样获取这个内存地址的值:

uint8_t value;
value = *ptr;

但是编译时出现错误:

Error C2440: '=' the conversion can not be done from 'Example_Struct' to 'uint8_t'

你能帮我只使用指针访问一个值吗? (没有名称引用 example_struct->a)

最佳答案

访问结构的第一个成员的简单示例。

// Example program
#include <iostream>
#include <string>
#include <cstddef>

struct example_struct{
uint8_t a;
uint16_t b;
float c;
};

int main()
{
example_struct a;
a.a =42;
uint8_t *ptr = (uint8_t*)&a;
float *fptr = (float *)(((uint8_t *)&a) + offsetof(EXAMPLE_STRUCT, c));

std::cout << "Hello, " << +(*ptr) << "!\n";
std::cout << "Hello, " << +(*fptr ) << "!\n";
}

关于c++ - 使用内存地址访问结构的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52929945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com