假设您有一台具有65536字节内存的16位计算机。 Int是2个字节。假设变量按照它们编码的顺序连续放入存储器,从存储器地址0x250开始。给出以下代码段:
int x = 30;
int y = 50;
int *px = &x;
int *py = &y;
printf("a) %x\n", px);
printf("b) %x\n", py);
px = py;
printf("c) %d\n", *px);
printf("d) %x\n", &px);
x = 88;
y = 14;
printf("e) %d\n", *px);
printf("f) %d\n", *py);
给出每个printf语句的输出。
他们说要假设内存地址按升序分配。
我得到了
a) 252
b) 254
c) 30
d) 250
e) 88
f) 14
这些是正确的吗?
答案 0 :(得分:4)
假设变量按编码顺序连续放入内存,从内存地址0x250开始
让我们按照nneonneo的提示,“作为第一遍,只需分配变量地址,这样你就知道一切都在哪里。”
这应该让你从右脚开始:
int x = 30; // &x = 0x250
int y = 50; // &y = 0x252
int *px = &x; // &px = 0x254
int *py = &y; // &py = 0x256
现在有点指导:
printf("a) %x\n", px); // These both print the *value* of the pointers
printf("b) %x\n", py); // themselves (in other words, the address to which
// they point).
// Note: they're printed in hexadecimal
// (unfortunately with no prefix).
px = py; // The *value* of py is assigned to px.
// Now they both point to the same thing.
printf("c) %d\n", *px); // This "de-references" px. In other words, it
// reads the value at the address px points to.
printf("d) %x\n", &px); // This prints the *address* of the pointer px.
// Hint: can this change during program execution?
x = 88; // Simple integer assignments
y = 14;
printf("e) %d\n", *px); // Same logic as c)
printf("f) %d\n", *py); // Same logic as c)
答案(对于那些想要检查答案或骗子的人):
a)250
b)252
c)50
d)254
e)14
f)14