我正在嘗試撰寫一個程式來模仿一些匯編代碼(不要問我為什么大聲笑),它應該看起來像這樣。
它應該使用 int 值來填充由 long 值組成的結構的記憶體。
當我除錯程式時,在第一次迭代中sizeof(int)*a = 0一切都很好。
但在第二次迭代中,a=1and sizeof(int)*1=4, but&ss sizeof(int)*a不等于&ss 4而是 to &ss 0xA0... 那么對于a = 2, &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]);
}
uj5u.com熱心網友回復:
正如user3386109所評論的, 的型別&ss是指向StructType1object的指標,因此向其添加一個整數會計算出此類物件陣列中第 -th 個物件n的地址,乘以物件的大小以獲取位元組地址。nn
出于您的目的,您應該將&ss其轉換為指向字符型別的指標。
這是修改后的版本:
#include <stdio.h>
#include <string.h>
typedef struct {
long a[5];
} StructType1;
StructType1 foo(void) {
StructType1 ss;
int bb = 7;
int a = 0;
int n = sizeof ss / sizeof(int);
while (a < n) {
memcpy((char *)&ss sizeof(int) * a, &bb, sizeof(int));
a ;
}
return ss;
}
int main() {
StructType1 s = foo();
for (int i = 0; i < 5; i ) {
printf("%ld%c", s.a[i], " \n"[i]);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/456469.html
