声明VS用C不声明数组 [英] Declared vs non-declared array in C

查看:264
本文介绍了声明VS用C不声明数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到code这两个块来

I came across these two blocks of code:

#include <stdio.h>
int main() {
  int a[10], i;
  for (i = 1; i <= 10; i++) {
    scanf("%d", &a[i]);
    printf("%d\n", a[i]);
  }
  return 0
}

当我运行的第一块code时,code运行良好,但它得到在某些时候无效,我没有得到预期的结果。

When I run the first piece of code, the code runs well but it gets overridden at some point and I do not get the expected result.

然而,当我跑第二件$ C $的c中的程序运行完全正常,没有错误。

However, when I run the second piece of code the program runs perfectly fine with no error.

#include <stdio.h>
int main() {
  int size;
  scanf("%d", &size);
  int a[size], i;
  for (i = 1; i <= size; i++) {
    scanf("%d", &a[i]);
    printf("%d\n", a[i]);
  }
  return 0
}

为什么程序在第二种情况下完美运行?即使在第二种情况下,下标变为过去的声明数组大小

Why does the program run perfectly in the second case? Even in the second case, the subscript goes past the declared array size.

推荐答案

这两个code段中数组越界访问让你看到未定义行为

Both code snippet has array out of bound access so you see undefined behavior

for(i=1;i<=size;i++)

如果您有规模的阵列 10 那么有效指数 0-9

If you have array of size 10 then the valid index is 0-9

在我们说未定义的行为,然后任何可能发生,甚至崩溃。当你说这是工作那么它仅仅是靠运气,你可能不会看到一个崩溃,但仍然要访问您还没有分配的一些内存

Once we say undefined behavior then anything might happen even a crash. When you say it is working then it is just by luck you might not be seeing a crash but still you are accessing some memory which you have not allocated

这篇关于声明VS用C不声明数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆