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 */
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)
);