简体   繁体   中英

C++ memcpy to end of an array

I'm trying to translate C++ into C# and I'm trying to understand, conceptually what the following piece of code does:

memcpy( pQuotes + iStart, pCurQuotes + iSrc, iNumQuotes * sizeof( Quotation ) );

pQuotes is declared: struct Quotation *pQuotes . pCurQuotes is a CArray of struct Quoataion , iSrc being it's first index. iNumQuotes is the number of elements in pCurQuotes .

What I would like to know is, if iStart is to pQuotes' last index, would the size of pQuotes be increased to accommodate the number of elements in pCurQuotes? In other words, is this function resizing the array then appending to it?

Thanks.

SethMo

If iStart is to pQuotes' last index, would the size of pQuotes be increased to accommodate the number of elements in pCurQuotes? In other words, is this function resizing the array then appending to it?

No.

This is a fundamental limitation of these low-level memory functions. It is your responsibility as the developer to ensure that all buffers are big enough so that you never read or write outside the buffer.

Conceptually, what happens here is that the program will just copy the raw bytes from the source buffer into the destination buffer. It does not perform any bounds- or type-checking. For your problem of converting this to C# the second point is of particular importance, as there are no type conversions invoked during the copying.

would the size of pQuotes be increased to accommodate the number of elements in pCurQuotes ?

No. The caller is expected to make sure before making a call to memcpy that pQuotes points to a block of memory sufficient to accommodate iStart+iNumQuotes elements of size sizeof(Quotation) .

If you model this behavior with an array Quotation[] in C#, you need to extend the array to size at or above iStart+iNumQuotes elements.

If you are modeling it with List<Quotation> , you could call Add(...) in a loop, and let List<T> handle re-allocations for you.

No, memcpy does not do any resizing . pQuotes is merely a pointer to a space in memory, and the type of pointer determines its size for pointer arithmetic.

All that memcpy does is copy n bytes from a source to a destination. You need to apply some defensive programming techniques to ensure that you do not write beyond the size of your destination, because memcpy won't prevent it!

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