Originally Posted by
matsp
Pointer arithmetic is valid only with subtract and only for pointers that point to the same block of memory (sure, you can do it for other pointers too, since the compiler doesn't actually check it - but the result is undefined, and quite often meaningless).
So ptr1 - ptr2 is valid if ptr1 and ptr2 are pointing to the same original block of memory. And you will get the "number of elements" between the two points - not the number of bytes between. So if it's char, int, struct FILE, or some other functions, it won't make any difference. Pointer arithmetic on void * is undefined.
--
Mats
Right, thanks.
One last question to wrap everything up (for now). Are the following implementations of memcpy and memove ok? I'm not quite sure if memmove is meant to do that.
Code:
/* memcpy - Copy memory from source to destination with the length of num. */
void * memcpy ( void * destination, const void * source, size_t num ) {
char* ptr_src=(char*)source,* ptr_dest=(char*)destination;
while(num--) *ptr_dest++ = *ptr_src++;
return destination;
}
/* memmove - Copy memory from source to destination with the length of num using a secondary buffer. This is useful for overlapping memory blocks. */
void * memmove ( void * destination, const void * source, size_t num ) {
char* buffer = new char [num];
memcpy((void*)buffer, source, num);
memcpy(destination, (void*)buffer, num);
delete[] buffer;
return destination;
}
And so I thank you once more and guarantee to you that this is the last topic to be discussed, not to bother you that much.
Jorl17
Edit: About the functions, I haven't altered them to fix the casts and all that, so don't comment on that please, I'm already fixing it