https://acm.ecnu.edu.cn/problem/2887/
指针确实令人头疼…这题最终还是问了同学才做出来,可能是CSAPP没学好??
因为最短的类型是两个字节的char,所以读入内容的时候用的char数组,之后的指针也声明的char*类型.随后移动指针到要读/写的地址,根据输入的类型进行强制转换并修改.
#include <bits/stdc++.h>
using namespace std;
int offset, len, n, pos, val;
char c, type[10], s[10005];
int main()
{
scanf("%X %d", &offset, &len);
for (int i = 0; i < len; ++i)
scanf("%2X", &s[i]);
scanf("%d", &n);
while (n--)
{
getchar();
scanf("%c %s %X", &c, type, &pos);
char *p;
p = s + pos-offset;
if (c == 'R')
switch (type[0])
{
case 'i': printf("%08X\n", *(unsigned int*)p); break;
case 's': printf("%04X\n", *(unsigned short*)p); break;
case 'c': printf("%02X\n", *(unsigned char*)p); break;
}
else
{
scanf("%X", &val);
switch (type[0])
{
case 'i': *(unsigned int*)p = (unsigned int)val; break;
case 's': *(unsigned short*)p = (unsigned short)val; break;
case 'c': *(unsigned char*)p = (unsigned char)val; break;
}
}
}
return 0;
}