11

How to memcpy the two dimensional array in C:

I have a two dimensional array:

int a[100][100];

int c[10][10];

I want to use memcpy to copy the all the values in array c to array a, how to do this using memcpy?

int i;
for(i = 0; i<10; i++)
{
    memcpy(&a[i][10], c, sizeof(c));
}

is this correct?

3
  • 1
    That depends on where you want the values to go. It looks like not quite what you probably want. Commented Jun 3, 2013 at 12:00
  • 6
    You have 100 times the capacity in a. Which elements of a do you want to hold a copy of c? Commented Jun 3, 2013 at 12:00
  • More like sizeof(c[i]), non? Commented Jun 3, 2013 at 12:00

3 Answers 3

13

That should work :

int i;
for(i = 0; i<10; i++)
{
    memcpy(&a[i], &c[i], sizeof(c[0]));
}
Sign up to request clarification or add additional context in comments.

Comments

3

It should actually be:

for(i = 0; i < 10; ++ i)
{
  memcpy(&(a[i][0]), &(c[i][0]), 10 * sizeof(int));
}

2 Comments

when I try to do &(c[i][0]), it tells me that error: no match for 'operator[]' in '*(c+ 924u)[0]'
You sure you typed it right? My compiler tells me nothing.. Which compiler are you using?
1

I don't think it's correct, no.

There's no way for memcpy() to know about the in-memory layout of a and "respect" it, it will overwrite sizeof c adjacent bytes which might not be what you mean.

If you want to copy into a "sub-square" of a, then you must do so manually.

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.