Reputation: 99
Assuming that I have initialized an int array using double pointer
int **array;
I have used malloc to give the wanted size of the array like this
array = malloc( sizeof *array * ROWS );
if ( array ){
for ( size_t i = 0; i < ROWS; i++ )
*(array + i) = malloc( sizeof *(*(array + i)) * COLS );
}
Every index of the array is declared with a random int number. I am trying to find a faster way to copy a row or a column rather than using for loops. My choice is to use memcpy, it looked like a good idea on the beginning since I had no problem copying a row using
memcpy((array + 1), (array + 3), (int)sizeof(int **));
However when it comes to columns using
memcpy(*(array + 1), *(array + 3), (int)sizeof(int *));
does not actually worked as I expected and only one element was copied. Is there something that I am missing?
Upvotes: 0
Views: 772
Reputation: 72479
For a 2D array, if your rows are laid out continuously in memory (aka row-major array) then your columns will not be continuous.
memcpy
, on the other hand, copies only continuous chunks of memory. Therefore you can't copy the entire column with just one call to memcpy
. You'll rather need to copy each element one-by-one, for which you don't need memcpy
.
Upvotes: 4