Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

Memory Fragmentation in C++

I want to use malloc()/new to allocate 256KB memory to variable m. Then, use m to store data such as strings and numbers. My problem is how to save data to m and retrive them.

For example, how to store int 123456 in offsets 0 to 3 and read it to variable x? Or store "David" string from offset 4 to 8(or 9 with ) and then, retrive it to variable s?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can store an integer by casting pointers.

unsigned char *p = new unsigned char[256 * 1000];
*(int *) p = 123456;
int x = *(int *) p;

This is a terrible idea. Don't worked with untyped memory, and don't try to play fast and loose like you do in PHP because C++ is less tolerant of sloppy programming.

I suggest reading an introductory C++ textbook, which will explain things like types and classes which you can use to avoid dealing with untyped memory.

Edit: From the comments above, it looks like you want to learn about pointer arithmetic.

Don't use pointer arithmetic*.

* unless you promise that you know what you are doing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...