The third argument to memcpy
is the number of bytes to copy. You provided the number of int
s. Do this instead:
memcpy ( k_src,
&handle->_context._buf[0],
handle->_context._bufLen * sizeof(int)
);
Frage
I have defined:
#define arrayLengthInStruct 50
typedef struct {
struct {
int _buf[arrayLengthInStruct];
int _bufLen;
} _context;
} _handle;
in main()
_handle handlePtr;
_handle* handle = (_handle*) &handlePtr; // data is here
int* k_src = NULL; // to be loaded to
int i = 0;
handlePtr._context._bufLen = arrayLengthInStruct;
// initialize the source
for (i = 0; i < handlePtr._context._bufLen; i++) {
handlePtr._context._buf[i] = i+1;
printf("%d \t", handlePtr._context._buf[i]);
}
printf("\n");
k_src = malloc(sizeof(int)*(handlePtr._context._bufLen));
printf("Amount of data to copy: %d \n", handle->_context._bufLen);
memcpy ( k_src,
&handle->_context._buf[0],
handle->_context._bufLen
);
for (i = 0; i < handlePtr._context._bufLen; i++) {
printf("%d \t", k_src[i]);
}
printf("\n");
However, the copy is incomplete. What am I missing?
output: /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
Amount of data to copy: 50
1 2 3 4 5 6 7 8 9 10 11 12 13 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 */
Lösung
The third argument to memcpy
is the number of bytes to copy. You provided the number of int
s. Do this instead:
memcpy ( k_src,
&handle->_context._buf[0],
handle->_context._bufLen * sizeof(int)
);
Andere Tipps
You're missing the fact that memcpy
copies a number of bytes rather than integers. You need to multiply your array size by sizeof(int)
when using it with memcpy
.
On a little-endian machine with four-byte int
type, copying 50 bytes would give you what you see (50 / 4 = 12.5) though the last element 13
would depend on what was already in the destination memory.