本文介绍了C ++使用数组分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
关于此关于如何分配内存而不使用new或malloc,假设我有一个结构链表
concerning this question on how to allocate memory without using new or malloc, suppose I have a structure linked list
struct stack {
string info;
stack next*;
};
提供的答案说使用全局字节数组。如何通过分配全局字节数组来实现链表?
The answer provided says use global byte array. How would I implement an linked list by allocating to global byte array?
推荐答案
一种方法是在数据中声明一个内存池
One way is to have a memory pool declared in data segment and have your own memory allocation function.
char myMemoryPool[10000000]; // global variable (can be enclosed in namespace)
void* MyMemoryAlloc (size_t SIZE)
{
//... use SIZE
}
用法:
A* p = (A*)MyMemoryAlloc(sizeof(A) * 3);
或更准确地说,
template<typename T>
T* MyMemoryAlloc (unsigned int UNITS)
{
//... use (sizeof(A) * UNITS)
}
用法:
A *p = MyMemoryAlloc<A>(3);
这篇关于C ++使用数组分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!