gpt4 book ai didi

c - for 循环中 *(&a – i) 的含义。这是乘法吗?

转载 作者:行者123 更新时间:2023-11-30 19:56:05 24 4
gpt4 key购买 nike

我正在准备即将到来的考试,这时我发现了这个:

char a = 'a';
char b = 'b';
int ai[] = { 1, 2 };
int i = 0;

Assume that word size is 32 bits, that an int is 32 bits and that memory allocations are made in the reverse order to the declarations starting at address location 68.

Draw a diagram that shows the effect of executing the following lines of code.

for (i = 0; i < 8; i++)
*(&a – i) = 'z';

这可能听起来很奇怪,但我是 C 新手,这是我第一次看到 for 循环的乘法。对此 for 循环及其乘法的解释将不胜感激。

最佳答案

我认为我们可以假设这是一个理论问题,考虑到问题中未定义的附加假设(即字节顺序、填充) - 该问题是可以回答的。但是,正如@chux 指出的那样,针对这种行为有一些标准。因为,如果允许的话,代码会导致堆栈内存损坏。作为一道考试题,它实际上要求您绘制出哪些内存正在被损坏。

如果我正确地解释了问题,则内存的一种可能表示形式(假设整数是 LSB,有 1 个字节填充,并且声明顺序相反):


|地址|值(value)|描述 |
| ---- | -----| ------------------------------------------ |
| 55 | 55 0x00 | 0x00//int i = 0; |
| 56 | 56 0x00 | 0x00 |
| 57 | 57 0x00 | 0x00 |
| 58 | 58 0x00 | 0x00 |
| 59 | 59 0x01 | 0x01//int ai[] = { 1, 2 }; |
| 60| 0x00 | 0x00 |
| 61 | 61 0x00 | 0x00 |
| 62 | 62 0x00 | 0x00 |
| 63 | 63 0x02 | 0x02 |
| 64 | 64 0x00 | 0x00 |
| 65 | 65 0x00 | 0x00 |
| 66 | 66 0x00 | 0x00 |
| 67 | 67 0x62 | 0x62//字符 b = 'b'; |
| 68 | 68 0x61 | 0x61//字符 a = 'a'; |

循环展开后的计算结果为:


[68] = 0x7a;//'z';
[67] = 0x7a;//'z';
[66] = 0x7a;//'z';
[65] = 0x7a;//'z';
[64] = 0x7a;//'z';
[63] = 0x7a;//'z';
[62] = 0x7a;//'z';
[61] = 0x7a;//'z';

因此,由变量 a、b 和 ai[] 数组的部分表示的内存将被损坏。 (合并了 @chux 关于字节顺序的观察。此外,我根据 @chux 和 @Peter A. Schneider 评论调整了 ai[] 元素出现的顺序。)


|地址|值(value)|描述 |
| ---- | -----| ---------------------------------------------------- |
| 55 | 55 0x08 | 0x08//int i = 8; |
| 56 | 56 0x00 | 0x00 |
| 57 | 57 0x00 | 0x00 |
| 58 | 58 0x00 | 0x00 |
| 59 | 59 0x01 | 0x01//int ai[] = { 0x7a7a0001, 0x7a7a7a7a }; |
| 60| 0x00 | 0x00 |
| 61 | 61 0x7a | 0x7a | |
| 62 | 62 0x7a | 0x7a | |
| 63 | 63 0x7a | 0x7a | |
| 64 | 64 0x7a | 0x7a | |
| 65 | 65 0x7a | 0x7a | |
| 66 | 66 0x7a | 0x7a | |
| 67 | 67 0x7a | 0x7a |//字符 b = 'z'; |
| 68 | 68 0x7a | 0x7a |//字符 a = 'z'; |

关于c - for 循环中 *(&a – i) 的含义。这是乘法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41600400/

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