[英]C Weird & interesting program output
I've written the following code in C: 我在C中编写了以下代码:
#include <stdio.h>
#include <stdlib.h>
#define LEN 100
int main(void)
{
int arr[LEN];
int i;
for (i = 0; i < LEN; i++)
printf("%d ", arr[LEN]);
getchar();
return 0;
}
First, notice I'm deliberately accessing memory which isn't part of the array (the last cell will be in index LEN-1
and I'm accessing arr[LEN]
, not arr[i]
. 首先,注意我故意访问不属于数组的内存(最后一个单元格将在索引
LEN-1
,我正在访问arr[LEN]
,而不是arr[i]
。
The weird result is that when I run the program, it prints all the numbers between 0 to... LEN-1. 奇怪的结果是,当我运行程序时,它会打印0到... LEN-1之间的所有数字。 For exmaple, when LEN defined to be 100 like here, the output is:
例如,当LEN像这里定义为100时,输出为:
0 1 2 ..... 99 0 1 2 ..... 99
Please run the program. 请运行该程序。 Does it happens to you too?
你也遇到过这种情况吗? I think this is platform-dependant behavior.
我认为这是与平台相关的行为。 (If it is relevant, I ran this code on Windows 7.)
(如果相关,我在Windows 7上运行此代码。)
Why does the value of arr[LEN] change? 为什么arr [LEN]的值会发生变化?
The stack is where local variables are kept. 堆栈是保存局部变量的地方。 Your compiler is using the memory location after the array (
arr[LEN]
basically) to keep i
. 你的编译器正在使用数组后的内存位置(基本上是
arr[LEN]
)来保持i
。 Therefore you are accidentally printing out i
on each iteration. 因此,您在每次迭代时意外打印出
i
。 A different compiler might keep i
somewhere else and you wouldn't see the same thing. 一个不同的编译器可能会让
i
其他地方,你不会看到同样的事情。
To expand on the answers of others, consider the following: 要扩展其他人的答案,请考虑以下事项:
Code 码
#include <stdio.h>
#include <stdlib.h>
#define LEN 100
int main(void)
{
int i;
int arr[LEN];
printf("&arr[LEN]: %p\n", &arr[LEN]);
printf("&i: %p\n", &i);
return 0;
}
Output 产量
&arr[LEN]: 0x7fff5cf90a74 &i: 0x7fff5cf90a74
On my machine, if i
is declared before arr
, i
and arr[LEN]
have the same address. 在我的机器上,如果
i
在arr
之前声明, i
和arr[LEN]
具有相同的地址。
Run the following on your machine 在您的计算机上运行以下命令
#include <stdio.h>
#include <stdlib.h>
#define LEN 100
int main(void)
{
int arr[LEN];
int i;
printf("&arr[LEN]: %p\n", &arr[LEN]);
printf("&i: %p\n", &i);
return 0;
}
You should see something very similar (addresses different, of course) to what I saw. 您应该看到与我所看到的非常相似的东西(当然,地址不同)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.