不能使用memcpy填充结构
我正在尝试编写一个程序来模仿一些装配代码(不要问我为什么大声笑),看起来应该这样。
它应该使用int值以填充由长值组成的结构的内存。
当我调试程序时,在第一次迭代sizef(int)*a = 0
中,一切都很好。
但是在第二个迭代中,a = 1
和sizeof(int)*1 = 4
,但& ss+sizeof(int)*a
不等于& ss+4
,而是& ss+0xa0
...然后为a = 2
,<代码>&amp; ss+0x140 。它不断乘以40(十进制系统)。
十六进制0xa0
= 4*40
十进制。十六进制0x140
= 8*40
十进制...
如何使此工作?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
long a[5];
} StructType1;
StructType1 foo()
{
StructType1 ss;
int bb = 7;
int a = 0;
while (a < 10)
{
memcpy(&ss + sizeof(int) * a, &bb, 4);
a++;
}
return ss;
}
int main()
{
StructType1 s = foo();
printf("%ld\n", s.a[0]);
}
I am trying to write a program to mimic some assembly code(don't ask me why lol), and it should look something like this.
It should use int value in order to populate the memory of the structure that consists of long values.
When I debug the program, in the first iteration sizeof(int)*a = 0
and everything is good.
But in the second iteration, a=1
and sizeof(int)*1=4
, but &ss+sizeof(int)*a
is not equal to &ss+4
but rather to &ss+0xA0
... Then for a = 2
, &ss+0x140
. It is constantly multiplying by 40 (decimal system).
hex 0xA0
= 4*40
decimal. hex 0x140
= 8*40
decimal...
How to make this work?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
long a[5];
} StructType1;
StructType1 foo()
{
StructType1 ss;
int bb = 7;
int a = 0;
while (a < 10)
{
memcpy(&ss + sizeof(int) * a, &bb, 4);
a++;
}
return ss;
}
int main()
{
StructType1 s = foo();
printf("%ld\n", s.a[0]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如user3386109所评论的,
&ss
的类型是指向StructType1
对象的指针,因此添加了一个整数n
计算此类对象数组中第n
个下一个对象的地址,将n
乘以该对象的大小即可获取字节地址。出于您的目的,您应该将
&ss
转换为指向字符类型的指针。这是修改后的版本:
As commented by user3386109, the type of
&ss
is pointer to aStructType1
object, thus adding an integern
to it computes the address of then
-th next object in an array of such objects, multiplyingn
by the size of the object to the get the byte address.For you purpose, you should cast
&ss
as a pointer to a character type.Here is a modified version: