开发者

Question on Pointer Arithmetic

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 l开发者_StackOverflowist. 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!


Pointer arithmetic uses the size of the underlying type. If int is 4 bytes:

int *p = some_address;
p++; 

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.


int *tailEnd = ( int* ) ( previousPlace->head_ptr + ((previousPlace->size+1)*(sizeof(int)) );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜