假设您有一台 16 位机器,内存为 65536 字节。整数为 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
这些正确吗?
最佳答案
Assume that variables are placed in memory contiguously in the order they are coded, starting at memory address 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
block 引用>
b) 252
c) 50
d) 254
e) 14
f) 14
关于c - 内存寻址和指针练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33136730/