C ++中的内存碎片 [英] Memory Fragmentation in C++

查看:171
本文介绍了C ++中的内存碎片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用malloc()/ new为变量m分配256KB内存。
然后,使用m来存储字符串和数字等数据。
我的问题是如何将数据保存到m并检索它们。

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.

例如,如何将int 123456存储在偏移量0到3中, X?
或者从偏移量4到8存储David字符串(或使用\0存储9个字符串),然后将其转换为变量s?

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 \0) and then, retrive it to variable s?

推荐答案

您可以通过转换指针来存储整数。

You can store an integer by casting pointers.

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

这是一个可怕的想法。不要使用无类型的内存,不要尝试像在PHP中一样快速和松散,因为C ++不太容忍粗糙的编程。

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.

我建议阅读一个介绍C ++的教科书,它将解释诸如类型和类之类的东西,你可以用它来避免处理无类型的内存。

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.

编辑

*,除非你答应你知道你在做什么。

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

这篇关于C ++中的内存碎片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆