JoseJimRin
JoseJimRin

Reputation: 402

Accessing a value of an attribute of a struct using memory address

I am trying to improve my knowledge using pointers in C++ and I want to access to the value of an attribute of a struct by a memory address. I have this struct defined:

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

I want to get the value of a usign the memory address (not the name of the attribute):

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

At this momment, I have in ptr the memory address value of the first element in the struct. So, I think this is the memory address of a variable. Then I tried to get the value of this memory address just like:

uint8_t value;
value = *ptr;

But I have an error on compilation:

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

Could you help me to access a value using only pointers? (without name reference example_struct->a)

Upvotes: 2

Views: 7292

Answers (2)

Xaqq
Xaqq

Reputation: 4386

A simple example to access the first member of the struct.

// 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";
}

Upvotes: 2

Petar Velev
Petar Velev

Reputation: 2355

You cannot access the first element of the structure as you would access the first element of an array( with [0]). Structure elements are accessed only by name.

If you want to get the address of the structure you can do it like this.

typedef struct example
{
    int a;
} Example_Struct;

Accessing elements.

Example_Struct exampleStruct;
exampleStruct.a = 5; // accessing the first element

Example_Struct* structPtr = &exampleStruct; // pointer to the structure
structPtr->a = 10; // accessing the first element

int* intPtr = &(exampleStruct.a); // pointer to the first element of the struct
int* intPtr2 = &(structPtr->a) // also pointer to the first element

There is a way to access the first element without using its name but it's not a good practice.

The structure is only a place in memory where you store your data. So casting the pointer to the structure to another type will give you the memory represented as this type.

Example_Struct exampleStruct;
int* firstElPtr = (int*)&exampleStruct; //representing the memmory as an int
int firstEl = *((int*)&exampleStruct); //representing and dereferencing the memmory as an int

Note that the point of creating a structure is that the elements can be accessed by their names and it is safe and most performant. If you want to do such things better use an array of uint8 or you may have issues with memory alignment.

Upvotes: 1

Related Questions