已分配空间中的链表
Linked list in allocated space?
我希望这个问题不需要过多的讨论,而是需要一个明确的答案。
我在大学里学了C,然后开始写我的第一个有用的程序(意思是没有规范)。我只是偶然发现了一个问题,我到目前为止还没有处理过,我想他们在讲座中没有提到:
当我分配可能被调整大小的内存时,我不应该存储指向该分配空间地址的指针。因为当我重新分配时,空间可能会被移动到另一个位置,这使得指向该区域的每个指针都毫无价值。这让我得出结论,我不能在空间中存储链表,每个元素都"存在"在这个空间的某个地方,因为重新分配可能会使所有的"next"answers"prev"指针失效。
这是一个问题,我从来没有遇到过,这就是为什么我想问你是否有一些解决方案。具体来说:我有一个共享内存区域,并希望将所有数据存储在其中,以便不同的进程可以在其中工作。由于数据(字符串)将被频繁地添加和删除,并且必须按照特定的顺序,我认为链表将是最好的方法。现在我意识到我不能这样做。还是我太盲目,看不到显而易见的解决方案?你会怎么做呢?(我不想把所有的东西都存储在一个文件中,它应该留在(主)内存中)
感谢并致以最良好的问候。菲尔。
这可以以牺牲简单性和性能为代价来完成。与在共享内存中存储指针不同,您必须存储从区域开始的偏移量。然后,当您想要"解引用"其中一个时,您可以将偏移量添加到指向共享区域的指针上。
为了避免错误,我会根据实际使用的语言为其创建一个特殊类型
C //seriously, this is one situation where I would find a global justified
region_ptr region;
//store these instead of pointers inside the memory region
struct node_offset {ptrdiff_t offset};
//used to get a temporary pointer from an offset in a region
//the pointer is invalidated when the memory is reallocated
//the pointer cannot be stored in the region
node* get_node_ptr(node_offset offset)
{return (node*)((char*)region+offset.offset);}
//used to get an offset from a pointer in a region
//store offsets in the region, not pointers
node_offset set_node_ptr(region* r, node* offset)
{node_offset o = {(char*)offset.offset-(char*)region}; return o;}
c++ //seriously, this is one situation where I would find a global justified
region_ptr region;
//store these in the memory region
//but you can pretend they're actual pointers
template<class T>
struct offset_ptr {
offset_ptr() : offset(0) {}
T* get() const {return (T*)((char*)region + offset);}
void set(T* ptr) {offset = (char*)ptr - (char*)region;}
offset_ptr(T* ptr) {set(ptr);}
offset_ptr& operator=(T* ptr) {set(ptr); return *this;}
operator T*() const {return get();}
T* operator->() const {return get();}
T& operator*() const {return *get();}
private:
ptrdiff_t offset;
};
template<class T>
struct offset_delete {
typedef offset_ptr<T> pointer;
void operator()(offset_ptr<T> ptr) const {ptr->~T();}
};
//std::unique_ptr<node, offset_delete<node>> node_ptr;
另一种与Mooing Duck建议的偏移量方法非常相似的方法是数组和数组索引。
如果每个列表元素的大小相同,则声明一个指向这些列表元素的数组的指针。将该指针设置为内存区域的开头。存储数组偏移量,而不是prev和next节点的指针。现在编译器会帮你添加偏移量
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 链表,反向函数,数据结构
- 使用std::list创建循环链表
- 链表的泛型函数remove()与成员函数remove)
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 我们可以删除链表中静态内存中的节点吗
- C++,指针数组,指向双链表中的条目
- 链表中写入访问冲突的未知原因
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 打印所有链表的元素 (C++)
- 错误:需要类名(链表c++)
- 为什么C中的通用链表中存储的数据已损坏
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 链表c++插入,所有情况都已检查,但没有任何工作
- 使用递归在常量空间和线性时间中向后打印链表
- 删除链表中的节点后释放分配的空间
- 已分配空间中的链表