Turbo C 阵列问题
可能的重复:
Turbo C 数组问题
#include <stdio.h>
#define LIM 40
int main()
{
int day=0;
float temp[LIM];
do
{
printf("Enter temperature for day %d.", day);
scanf("%f", &temp[day]);
}
while(temp[day++] && day<LIM );
}
关于最后一行。为什么不满足while(temp[day++] > 0)
?因为我已将 LIM 设置为 40?为什么我应该添加一些附加条件,例如 day
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为,如果您输入 41 个数字,您将写入数组外部的位置,从而调用可怕的未定义行为。当您尝试写入
temp[40]
(第 41 个元素)时,您可能会破坏不应该破坏的内存。它可能可以在数组末尾之外工作一点,但这就是未定义行为的本质。这仍然不是一个好主意。日
当您输入 40 个温度时,LIM 位将强制退出循环,无论您实际输入的值是什么。
Because, if you enter 41 numbers, you will write to a location outside the array, invoking the dreaded undefined behaviour. When you attempt to write to
temp[40]
(the 41st element), you'll likely clobber memory that you shouldn't. It may work for a little bit beyond the end of the array but that's the nature of undefined behaviour. It's still not a good idea.The
day < LIM
bit will force the loop to exit when you've entered 40 temperatures, regardless of what value you've actually entered.以避免数组溢出。
temp
数组具有LIM
单元,您需要检查是否尝试访问超出该范围的内存,因为这会导致未定义的行为。如果您想获取超过 40 个元素,则应该为它们分配更多内存,这可以通过将
LIM
定义为更大的值来完成,例如#define LIM 48
。To avoid overflow of the array. The
temp
array hasLIM
cells, and you need to check that you don't try to access memory beyond that because it will cause an undefined behavior.If you want to get more than 40 elements, you should allocate more memory for them, which can be done by defining
LIM
to a bigger value, like#define LIM 48
.因为C不会魔法。它不会检查您是否超出了分配的内存。它无法知道访问是否有效,因此无论如何都会尝试。
Because C doesn't do magic. It doesn't check if you step outside the allocated memory. It can't know if an access is valid or not so it tries it anyway.