문제

I'm writing a class member function to remove a row from a (m x n) matrix. The memory model for the matrix (from a standard linear algebra library) is guaranteed to be a contiguous block such that the (i, j)th element maps to the (i * n + j)th element of that memory block.

I'd like to use ::memcpy for clarity and performance reasons. (The alternative ways using for loops are cumbersome.) But I need some reassurance.

In general, the destination location overlaps the source location since, if I'm deleting row r, I'd use (dropping any casts for clarity),

::memcpy(r * n, (r + 1) * n, bigger than n in general)

If ::memcpy is guaranteed to copy from the start of the block, then this will be fine. But, does the standard guarantee this? I can't see why it would and suspect the behaviour of such code is undefined.

도움이 되었습니까?

해결책

You should use memmove instead of memcpy. The overlapping behaviour for memmove is defined.

User thang pointed out in a comment, there is a related article which dicusses the difference between memcpy and memmove.

다른 팁

Have you considered using std::copy or std::copy_backwards?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top