Question

I have an array of doubles stored in a memory mapped file, and I want to read the last 3 entries of the array (or some arbitrary entry for that matter).

It is possible to copy the entire array stored in the MMF to an auxiliary array:

void ReadDataArrayToMMF(double* dataArray, int arrayLength, LPCTSTR* pBufPTR)
{
    CopyMemory(dataArray, (PVOID)*pBufPTR, sizeof(double)*arrayLength);
}

and use the needed entries, but that would mean copying the entire array for just a few values actually needed.

I can shrink arrayLength to some number n in order to get the first n entries, but I'm having problems with copying a part of the array that doesn't start from the first entry. I tried playing with pBufPTR pointer but could only get runtime errors.

Any ideas on how to access/copy memory from the middle of the array without needing to copy the entire array?

Was it helpful?

Solution

To find start offset for nth-element:

const double *offset = reinterpret_cast<const double*>( *pBufPTR ) + n;

To copy last 3 elements:

CopyMemory( dataArray, reinterpret_cast<const double*>( *pBufPTR ) + arrayLength - 3, 3 * sizeof(double) );

OTHER TIPS

You can just add the (0 based) index of the first array element you want to copy to the dataArray pointer value that you pass in... the pointer will be increased by the index times sizeof(double). Makes sure you pass in an arrayLength value reflecting the number of elements to operate on, and not the original array length.

For example, to copy the last 10 elements (assuming you've already checked there are at least 10 elements)...

ReadDataArrayToMMF(dataArray + arrayLength - 10, 10, &myBufPTR);

Similarly (albeit illustrating a different notation to get the address), to get elements 20..24:

ReadDataArrayToMMF(&dataArray[20], 5, &myBufPTR);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top