【发布时间】:2019-01-07 15:03:07
【问题描述】:
我发现 MSVC2017 中的 memcpy() 和 memset() 函数有些奇怪,我无法解释。具体来说,“目标”不是按单个字节索引,而是按结构的整个大小(“大小”参数)进行索引。
所以我有一个结构:
typedef struct _S
{
int x;
int y;
} S;
代码如下:
S* array = (S*)malloc(sizeof(S) * 10); /* Ok. Allocates enough space for 10 structures. */
S s; /* some new structure instance */
/* !!! here is the problem.
* sizeof(S) will return 8
* 8*1 = 8
* now the starting address will be: array+8
* so I'm expecting my structure 's' to be copied to
* the second ''element'' of 'array' (index 1)
* BUT in reality it will be copied to the 7th index!
*/
memcpy(array + (sizeof(S) * 1), &s, sizeof(S));
/* After some tests I found out how to access 'properly' the
* 'array':
*/
memcpy(array + 1, &s, sizeof(S); /* this will leave the first struct
in the 'array' unchanged and copy 's's contents to the second
element */
memset() 也一样。 到目前为止,我认为索引应该手动完成,同时提供复制对象的大小,但是没有?
memcpy(destination + (size * offset), source + (size * offset), size)
我做错了吗?
【问题讨论】:
-
阅读指针算法。如果
destination是S*你不必乘以大小 -
array + (sizeof(S) * 1)- 没有做你认为的那样。阅读指针算法。你想要array + 1。 -
array + 8不会将 8 添加到array。它增加了 8S的大小。在这种情况下,就像(char*)array + 64 -
很可能不是问题,但声明
_S的行为未定义。 -
那么你使用的不是C编译器,而是C++。您可能会发现其他问题。
标签: c visual-c++ memcpy memset