How do I copy a one-dimensional array to part of another two-dimensional array, and vice-versa?
Basically, I have three arrays, CQueue (2D-array), PQueue (2D-array, the same number of arrays as the CQueue, but with each array containing twice as many values) and CC (standard array which is as long as an array in the CQueue). What I want to achieve is taking a specific array in the CQueue, copying it so that CC reads exactly the same as CQueue, and so that the first half of the equivalent array in the PQueue also reads the same.
I've been advised to use memcpy by a friend, which seemed fine but hasn't fixed the problem. I don't know whether the problem 开发者_JAVA技巧lies within me potentially using memcpy incorrectly or whether there's another issue at hand. Following is a simplified version of the relevant part of the code.
int (main)
{
int CQueue[numberOfArrays][halfSize]
int PQueue[numberOfArrays][size]
int CC[halfSize]
for (i = 0; i < numberOfArrays]; i++)
{
memcpy (CC, CQueue[i], halfSize)
memcpy (PQueue[i], CQueue[i], size)
}
}
Any help offered would be much appreciated, thanks!
The third argument to memcpy
is the amount to copy in characters (i.e. bytes on most platforms). So you need to do something like:
memcpy(CC, CQueue[i], halfSize*sizeof(*CC));
memcpy
copies bytes, not ints. You need to multiply the number of elements to copy by the size of each such element
memcpy(dst, src, elems * sizeof elem);
in your code
memcpy (CC, CQueue[i], halfSize * sizeof *CC);
memcpy (PQueue[i], CQueue[i], size * sizeof *PQueue[i]);
精彩评论