Answer the question
In order to leave comments, you need to log in
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;
};
object o;
void *p = &o;
int offset1 = offsetof(struct object, a);
int offset2 = offsetof(struct object, b);
*((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;
}
Answer the question
In order to leave comments, you need to log in
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?
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;
}
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 questionAsk a Question
731 491 924 answers to any question