devxlogo

Indirectly working with a structure in C++

Indirectly working with a structure in C++

Question:
I am trying to create a class that can be given the pointer to a structure. The class has other means to know what goes into the structure, but it does not know the names of the elements within the structure.

By using just the address and knowing the data types can I use pointer math to move through the structure assigning values to the structure via only the address.

You may know of a better way than this.

Thanks,Bob

Answer:
I’m not sure exactly what you are doing but this should be possible. I would develop some sort of data that describes the structure being passed. For example, you might have a list of values, each one specifying the offset and size of each element.

You could initialize the offset using the offsetof macro, and of course the size using sizeof. If you passed this data to a class, along with the number of fields and the address of the structure, the class should be able to do whatever processing is needed.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist