gpt4 book ai didi

c - 棘手的指针问题

转载 作者:太空狗 更新时间:2023-10-29 16:38:49 25 4
gpt4 key购买 nike

我在从这个链接中找到的关于 c 中的指针的过去考试问题上遇到了问题, http://www.cl.cam.ac.uk/teaching/exams/pastpapers/y2007p3q4.pdf

问题是这样的:

A C programmer is working with a little-endian machine with 8 bits in a byte and 4 bytes in a word. The compiler supports unaligned access and uses 1, 2 and 4 bytes to store char, short and int respectively. The programmer writes the following definitions (below right) to access values in main memory (below left):

地址字节偏移量
----------0 --1-- 2-- 3
0x04 | 10 00 00 00
0x08 | 61 72 62 33
0x0c | 33 00 00 00
0x10 | 78 0c 00 00
0x14 | 08 00 00 00
0x18 | 01 00 4c 03
0x1c | 18 00 00 00

int **i=(int **)0x04;  
short **pps=(short **)0x1c;

struct i2c {
int i;
char *c;
}*p=(struct i2c*)0x10;

(a) 写下下列 C 表达式的值:

**i  
p->c[2]
&(*pps)[1]
++p->i

我明白了

**i == 0xc78  
p->c[2] == '62'
++p->i == 0x1000000

我不明白第三个问题(&(*pps)[1]),谁能解释一下这是怎么回事?我知道 pps 指针已被取消引用,但运算符的地址已应用于该值。这不就像要求一个常量的地址,例如如果我这样做了

int i = 7;  
int *p = &i;
&(*p) //would this mean address of 7??

在此先感谢您的帮助。

最佳答案

[]运算符优先于 &运算符(operator)。所以代码取消引用 pps获取 short* 数组的第一个元素.因为这个元素也是一个指针,我们可以把它当作一个数组,并在它指向的元素右边的一个位置查找元素,wth [1] .最后,我们获取该元素的地址。

注意 &p[i] 可能会有用与p + i相同- 它为您提供指向元素 i 的指针p右边的位置指向。

中间值是:

pps == 0x1c
*pps == 0x18
&(*pps)[1] == *pps + 1 == 0x1A

(+1 增加两个字节,因为它用在 short* 上)

关于c - 棘手的指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5465912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com