数组初始化在c ++? [英] Array initialization in c++?

查看:188
本文介绍了数组初始化在c ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{
    clrscr();
    int x[3];
    int n;
    cout<<"Enter the array size= ";
    cin>>n;
    cout<<"Enter the elements for array= ";
    for(int i=0;i<n;i++)
    {
        cin>>x[i] ;
    }
    for(i=0;i<n;i++)
    {
        cout<<"x["<<i<<"]="<<x[i]<<"\n";
    }
    getch();
    return 0;
}

当在c#中尝试同样的逻辑时,我输入数组的大小比我初始化它给出的异常。但在c ++ m没有得到任何类型的错误既不编译时间也不在运行时。但根据规则,它应该给出一些错误在运行时在输出如果我给阵列大小比我初始化。一个事情更多为什么它确定09作为两个numbrs不单单为90它显示它在不同的索引0和9在输出。

When m trying the same logic in c# then I got the right output as if I enter the size of array more than I initialize it gives the exception. But in c++ m not getting any type of error neither on compilation time nor at run time. But according to rule it should be give some error at run time in output if i give array size more than I initialize. And one thing more why it determine the 09 as two numbrs not single as 90 it shows it 0 and 9 at differect index as in output.

推荐答案

如果你有一个数组:

char array[3];

您尝试写入不存在的元素:

And you try to write into an element that doesn't exist:

array[15] = '!';

然后这个错误。但是,C ++标准不需要编译器来诊断此错误,大多数情况不会。这是因为每次访问数组时都需要计算来确定您是否在数组边界内。

Then this is an error. However, a compiler is not required by the C++ Standard to diagnose this error, and most do not. This is because it would require computation every time you accessed the array to determine whether you were within the array bounds.

而是它是由程序员确保他/她正确使用数组,这些边界检查自己。然后,只有当程序员认为必要时才执行检查,并且没有浪费的计算。

Instead, it is up to the programmer to ensure that he/she uses the array correctly, by writing these bounds checks his- or herself. Then the checks are only performed when the programmer has deemed them necessary, and there are no wasted computations.

因此:

std::cin >> n;

if (n > 3)
   throw std::runtime_error("OMG not enough space in my array!");

这篇关于数组初始化在c ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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