添加比分配空间更多的元素 [英] Adding more elements than allocated space

查看:142
本文介绍了添加比分配空间更多的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据结构类中,老师给了我们一个简单的代码,从一个循环的数组打印元素。我声明了一个包含10个元素的数组,但初始化了15个值为5的元素,而不是打印15个元素,知道其余的元素将显示垃圾值。但它只输出5个元素。事实上,它显示了我初始化数组的元素数量。我使用代码块13.12。
。提前感谢。

In my data structure class, teacher gave us a simple code to print elements from an array with a loop. I declared an array with 10 elements but initialized 15 elements with value 5 than printing 15 elements knowing that rest of elements will show garbage value. But it outputs only 5 elements. As a matter of fact it shows the number of elements I initialize the array to. I am using codeblocks 13.12. thanks in advance.

#include <iostream>
using namespace std;

int main(){
    int i,n;
    int arr[10];
    n=15;

    for(i=0;i<n;i++){
        arr[i] = 5;
    }

    for(i=0;i<n;i++){
       cout << arr[i] << endl;
    }

    return 0;
}


推荐答案

代码的行为未定义。通过推理它可能做什么很少获得。只需修复数组大小。 (有可能是一个超出界限的写入覆盖了 n 的值。

The behavior of the code is undefined. There is very little to be gained by reasoning about what it might do. Just fix the array size. (chances are that one of the out-of-bounds writes is overwriting the value of n).

这篇关于添加比分配空间更多的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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