Reputation: 601
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
Upvotes: 0
Views: 1185
Reputation: 955
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!
Upvotes: 1
Reputation: 726987
would the size of
pQuotes
be increased to accommodate the number of elements inpCurQuotes
?
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.
Upvotes: 1
Reputation: 54737
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.
Upvotes: 2