简体   繁体   中英

Pure C: Copy rows and columns of a 2D array using pointers

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM