0

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?

2
  • 3
    Why do you fancy the pointer notation, i.e *(array + 1); array[1] is simpler and more readable. Commented Apr 16, 2019 at 15:37
  • How would this "memcpy((array + 1), (array + 3), (int)sizeof(int **));" copy more bytes then the number of bytes a pointer of type int** uses (typically 4 or 8 bits depending on the OS)? Commented Apr 16, 2019 at 16:07

1 Answer 1

4

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.

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

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.