0

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 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!

3
  • the last argument in memcpy is the number of bytes to copy, so you should be copying X*sizeof(int), not just X Commented Jul 5, 2011 at 12:28
  • You want a specific array or all of them? You're iterating over all of them, which isn't what you described, and also wasteful, since CC ends up being written over many times and only the last value will remain. Commented Jul 5, 2011 at 12:30
  • What I posted was a simplified version only showing the relevant part of the problem - I'm doing a lot more stuff inside that for loop, but nothing that should have affect on this problem. Commented Jul 13, 2011 at 10:23

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

Comments

0

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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.