简体   繁体   中英

How to quickly get one dimensional int array from int **?

I would like to get one dimensional array from my double int pointer. The memory for pointer is allocated like this :

listOfTxtsContents = new int *[ROWS];
for( int i = 0 ; i < ROWS ; i++ )
{
    listOfTxtsContents[i] = new int[COLUMNS];
    for(int j = 0; j < COLUMNS; ++j)
        listOfTxtsContents[i][j] = 0;
}

Then each row contains some data where I would like to put it in the array in such a way so that the 1D array will be filled with consecutive rows.

Pretty sure something like this should work:

array[ROWS * COLUMNS];
for(size_t i = 0; i < ROWS; ++i)
  memcpy(array + i * COLUMNS, listOfTxtsContents[i], COLUMNS * sizeof(int));

Allocate a 1D array of ints of size ROWS*COLUMNS; assign each listOfTxtsContents[i][j] to element i*COLUMNS+j.

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