零大小的数组? [英] Array of zero size?

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

问题描述

我们一般在声明如下格式的数组:

Generally we declare the array in following format:

DataType array_name[SIZE];

所以,如果我尝试创建0长度数组例如

SO If I tried creating 0 length array for e.g.

int arr[0]; //Line#1
arr[0] = 5; //Line#2

在上面code为executed.In这种情况下,对单个整数内存分配我没有得到任何错误?

I do not get any error when above code is executed.In this case is memory allocated for single integer?

推荐答案

为什么1号线不产生任何编译错误?结果
理想情况下,它应该!结果
这是不合法的code创建大小 0 本地存储阵列。结果
理想情况下,编译器应该发出你一个错误,可能是一些编译器扩展允许这种编译,但按照标准,这不是C $ c.Try有效$与 -pedantic 。

Why does the Line#1 not generate any compilation error?
Ideally, it should!
It is not legal code to create an array of size 0 on local storage.
Ideally, the compiler should issue you an error, probably some compiler extension allows this to compile but as per the standard this is not a valid code.Try compiling with -pedantic.

参考:

C ++标准03 8.3.4 / 1:

如果该_constant-EX pression +(5.19)是present,它应是一个整型常量前pression其值应大于零。

If the _constant-expression+ (5.19) is present, it shall be an integral constant expression and its value shall be greater than zero.

此外,结果
为什么2号线不产生任何编译错误?结果
因为写超越分配的数组的边界就是未定义行为即可。不确定的行为并不需要编译器为您提供任何诊断。需要注意的是,一旦code表现出未定义行为字面上任何事情都有可能发生,所有的赌注都关闭。

Further,
Why does the Line#2 not generate any compilation error?
Because writing beyond the bounds of an allocated array is Undefined Behavior. An Undefined Behavior does not need the compiler to provide you any diagnostic. Note that once the code exhibits an Undefined Behavior literally anything can happen and all bets are off.

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

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