关于指针运算的问题
大家好! 我正在尝试创建一个内存管理系统,以便用户可以调用我创建的方法 myMalloc。我有一个链接列表来跟踪我的空闲内存。我的问题是当我试图在链接列表中找到空闲位的末尾时。我试图将该部分(位于链接列表中)中的空闲内存大小添加到指向可用空间前面的指针,如下所示。
void *tailEnd = previousPlace->head_ptr + ((previousPlace->size+1)*(sizeof(int));
我希望这能给我一个指向该段结尾的指针。但是,我不断收到警告:
“算术中使用类型为‘void*’的指针”
有更好的方法吗?谢谢!
Heyy Everybody!
I am trying to create a memory management system, so that a user can call myMalloc, a method I created. I have a linked list keeping track of my free memory. My problem is when I am attempting to find the end of a free bit in my linked list. I am attempting to add the size of the memory free in that section (which is in the linked list) to the pointer to the front of the free space, like this.
void *tailEnd = previousPlace->head_ptr + ((previousPlace->size+1)*(sizeof(int));
I was hoping that this would give me a pointer to the end of that segment. However, I keep getting the warning:
"pointer of type 'void*' used in arithmetic"
Is there a better way of doing this? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
指针算术使用基础类型的大小。如果 int 为 4 个字节:
将使 p 增加 4 个字节。 void 不能用于指针算术,因为 void 没有与之关联的大小。如果要对 void 指针执行字节大小的算术,则需要将指针转换为字节大小的类型。
Pointer arithmetic uses the size of the underlying type. If int is 4 bytes:
will increment p by 4 bytes. void can't be used in pointer arithmetic because void has no size associated with. If you want to do byte-sized arithmetic on void pointers, you need to cast the pointers to a byte-sized type.