【问题标题】:Incomplete copy from struct to array从结构到数组的不完整复制
【发布时间】:2014-02-07 22:02:13
【问题描述】:

我已经定义了:

 #define arrayLengthInStruct 50

 typedef struct {
  struct {
        int _buf[arrayLengthInStruct];           
        int _bufLen;
 } _context;
} _handle;

在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");

但是,副本不完整。我错过了什么?

输出: /* 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

要复制的数据量: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 */

【问题讨论】:

    标签: c arrays struct memcpy


    【解决方案1】:

    memcpy 的第三个参数是要复制的字节数。您提供了ints 的数量。改为这样做:

    memcpy ( k_src,
    &handle->_context._buf[0],
     handle->_context._bufLen * sizeof(int)
    );
    

    【讨论】:

      【解决方案2】:

      您错过了 memcpy 复制多个 字节 而不是整数的事实。与memcpy 一起使用时,您需要将数组大小乘以sizeof(int)

      在具有四字节 int 类型的 little-endian 机器上,复制 50 个 字节 将得到您所看到的 (50 / 4 = 12.5),尽管最后一个元素 13 取决于关于目标内存中已经存在的内容。

      【讨论】:

        猜你喜欢
        • 2012-09-02
        • 2015-01-06
        • 1970-01-01
        • 1970-01-01
        • 2019-09-03
        • 2016-10-13
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多