gpt4 book ai didi

C++使用数组分配内存

转载 作者:行者123 更新时间:2023-11-30 02:08:40 26 4
gpt4 key购买 nike

关于这个question关于如何在不使用 new 或 malloc 的情况下分配内存,假设我有一个结构链表

struct stack {
string info;
stack next*;

};

提供的答案说使用全局字节数组。如何通过分配给全局字节数组来实现链表?

最佳答案

一种方法是在数据段中声明一个内存池,并有自己的内存分配函数。

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++使用数组分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6326907/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com