A
A
Anton Nadtoka2016-04-21 17:17:43
Programming
Anton Nadtoka, 2016-04-21 17:17:43

How to access structure elements by pointer (C++)?

How can you access the members of a structure?
There is a pointer to void * (points to a specific structure). Example:

struct object
{
int a;
std::string b;
};

i have a pointer -
object o;
void *p = &o;

you can find the offset in memory by pointer:
int offset1 = offsetof(struct object, a);
int offset2 = offsetof(struct object, b);

for example int can i set: the question is how to set std::string? if I bring to the pointer - I get porridge. The option to use a pointer to std::string in the structure is not suitable. There are options? --- Although I checked it works like this:
*((int *) (p + offset1)) = 5;
#include <iostream>
#include <string>

struct object
{
    int a;
    std::string b;
};

int main(int argc, const char * argv[]) {
    
    object o;
    char *p = (char *) &o;
    
    o.a = 1;
    o.b = "demo";
    
    int offset1 = offsetof(struct object, a);
    int offset2 = offsetof(struct object, b);
    
    *((int *) (p + offset1)) = 5;
    *((std::string *) (p + offset2)) = std::string("demoooo");
    
    return 0;
}

I used wxString (wxwidgets) - apparently there are some problems.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Martyanov, 2016-04-21
@vilgeforce

object* optr = (object*)p;
optr->b = "foobar";
not an option, okay.
unsigned char* addr = (unsigned char*)o;
addr = addr + offset2;
std::string* strPtr = (std::string*)addr;
*strPtr = "foo";
Option two is also not an option?

P
Peter, 2016-04-21
@petermzg

1. std::string is a class, so there will be a pointer to a class object in the structure.
2. The offset within the structure can be different for different compilers, it depends on the data alignment settings.
3. There is also such a syntax

struct Object{
        bool m_fVisible			: 1;
  bool m_fEnable			: 1;
  bool m_fEntered			: 1;
  bool m_fTopmost			: 1;
  bool m_fSimple			: 1;
  bool m_fParentCursor	: 1;
  bool m_fClickEvent		: 1;
  bool m_fRedrawEnter		: 1;
  bool m_fWheelEvent		: 1;
}

What will you do in this case?

I
Ivan Bogachev, 2016-04-21
@sfi0zy

Perhaps I did not quite understand the question, but why not use

object o;
void *p = &o;
((struct object*)p)->b = "hello";
std::cout << ((struct object*)p)->b; // hello

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question