0

Say I have

struct S{

int m[10];

};

I can easily save this to a file by simply using:

S s;

file.write(reinterpret_cast<char*>(&s), sizeof(S));

But what if I have dynamic arrays within the struct? Is there an easier way to save a struct with arrays to a file, without having to iterate over each element within each array in the struct?

struct S2{
int *p;
int *t;
};
5
  • note that your way to serialize S doesn't manage endianess. Commented Dec 30, 2013 at 18:54
  • You are trying to flatten the struct. So nope. Commented Dec 30, 2013 at 18:55
  • Sorry, but what do you mean by "serialize" S? Commented Dec 30, 2013 at 18:56
  • @user3140280 serialization is what you're doing. Commented Dec 30, 2013 at 18:58
  • Okay, thanks Dave. But when I save it like that, each integer is correctly stored with the correct serialization, and can be read by the program again with no problems. Each integer takes 4 bytes and is stored as little-endian. Commented Dec 30, 2013 at 19:04

1 Answer 1

2

No, there is not. And you shouldn't write to a file the way you demonstrated either. You should always serialize each member separately.

Classes and structs may have padding. If you write out the structure from one version of the program and read it in using another version of the program, the structure size and layout may not line up. This is also true if you have a cross platform application, or if different programs are reading/writing this file. Serializing each member separately also gives you the chance to swap endianness if needed for networking/cross platform purposes.

Sign up to request clarification or add additional context in comments.

1 Comment

"You should always serialize each member separately." You mean I should store it byte by byte? Basically converting it to base 256? I don't really need to worry about any potential future problems with this program. I just need it to work for now and as naive and as simple as easy as possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.