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

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

问题描述

在我的数据结构课上,老师给了我们一个简单的代码,用循环打印数组中的元素.我声明了一个包含 10 个元素的数组,但使用值 5 初始化了 15 个元素,而不是打印 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天全站免登陆