解引用已知大小的void指针以将值添加到数组 [英] dereferencing void pointer of known size to add value to an array

查看:92
本文介绍了解引用已知大小的void指针以将值添加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好:)

我想创建一个通用列表,但是我希望数据紧凑,因此我使用了一个数组,我想在其中添加元素的值,而不是元素的指针.我该怎么办?

到目前为止,我有什么:
-在构造函数中,我得到元素的数量和一个元素的尺寸.
-一个无效的* list,我将其分配为number_elements * dimension;
-添加时,我得到一个空的*指针,并将其添加到索引位置为
list [index * dimension],但是我不知道如何取消引用void指针来添加值而不是指针,因为指针可能指向一些临时数据,并且我希望列表紧凑,而不是传播到内存中的所有位置,以备以后使用.

谢谢:)

Hi there:)

I want to create a generic list, but I want the data to be compact, so I use an array into which I want to add the values of the elements, not the pointers to the elements. How could I do that?

What I have so far:
-In the constructor I get the number of elements and the dimension of one element.
-A void *list, which I allocate as number_elements*dimension;
-When I add, I get a void *pointer, and I add it to the index position as
list[index*dimension], but I don''t know how to dereference the void pointer as to add the value, not the pointer, because the pointer may point to some temporary data, and I want the list to be compact, not spread everywhere in the memory, for a later memcpy.

Thank you :)

推荐答案

Awooga!在与通用编程有关的任何事情中提到空指针和memcpy通常都表明您做错了事...

根据您上面所描述的,std :: vector会做您想要的.如果不是,那就是您应该在列表实现中使用的想法.

干杯,

Ash
Awooga! Mentions of void pointers and memcpy in anything to do with generic programming is usually a sign that you''re doing something wrong...

From what you''re describing above std::vector will do what you want. And if it doesn''t it''s what you should be thinking of using in your list implementation.

Cheers,

Ash


如果您正在参加C ++课程,则应该使用std :: vector.如果您不确定,请问您的教授是否可以安排您的作业.

如果您不参加C ++课程,请使用std :: vector.

真的.

避免使用C ++编译器回退到C实现的诱惑.如果您正在学习C ++,请学习并利用它的强大功能.
If you''re attending a C++ course, you should really be using std::vector. Ask your professor if that''s ok for your assignment if you are unsure.

If you''re not attending a C++ course, use std::vector.

Really.

Avoid the temptation of falling back to C implementations using a C++ compiler. If you are learning C++, learn and make use of it''s powerful features.


这是常见的模式,当您希望将所有内容紧密地放在内存中以提高缓存性能时.如果您研究std :: vector的vc或gcc实现,您会发现它们使用void *和new放置会做一些有趣的事情.向量非常好,可以满足99%的情况,但有时并不完全符合您的需求.

还有很多模板的乐趣.

您可以在数组中调用该类型的构造函数,复制构造函数和析构函数吗?可能还会为您带来更多分数.
This is common pattern when you want to keep things close together in memory for cache performance. If you look into the vc or gcc implementations of std::vector you''ll see they do interesting things with void* and placement new. vector is great and suits 99% of cases but sometimes its not exactly what you need.

There is lots of template fun to be had as well.

Can you invoke the constructor, copy constructor and destructor of the type in the array? Might get you some more marks.


这篇关于解引用已知大小的void指针以将值添加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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