3

Refering to http://www.devx.com/tips/Tip/13291, it says that I can use memcpy with the size to copy determined by sizeof(), however, isn't the array pointing to a pointer?

Other than iterating through the array, how can I use memcpy to deep copy an array?

Thanks!

1
  • 2
    Arrays are not pointers, no matter what anyone tries to tell you. Commented Feb 14, 2011 at 9:35

3 Answers 3

8

In the linked example int weekly_hours[5][5]; allocates space for 25 integers. There is no further indirection, so you can safely use memcpy to duplicate it's values.

Sign up to request clarification or add additional context in comments.

Comments

6

A multi-dimensional array is contiguously allocated. An array of pointers (of pointers...) is a different thing (and each sub-pointer should be allocated/copied/freed on its own).

Do not be confused by the fact that an unidimensional array and a single pointer can be used interchangeably in most situations, because they are not technically the same.

Comments

4

To hopefully clear up some of the confusion:

  • An array is a chunk of allocated, adjacent memory cells.
  • An array variable name can transform ("decay") into a pointer to the first element of the array, but not the other way around. This is done implicitly each time you use the array variable name in pointer arithmetics.
  • You can use the sizeof() operator on the variable name of any statically alloced array, to get the number of bytes in the array. If sizeof() is used on a statically allocated, multi-dimensional array, the same applies.
  • If you use the sizeof() operator on a pointer, you will get the size of a pointer (i.e. 4 bytes on a 32-bit machine).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.