声明负长度的数组 [英] Declaring an array of negative length

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

问题描述

在C当您创建负长度的数组,会发生什么?

What happens in C when you create an array of negative length?

例如:

int n = -35;

int testArray[n];

for(int i = 0; i < 10; i++)
    testArray[i]=i+1;

这code编译(并带来了-Wall没有警告启用),似乎可以分配给 testArray [0] 没有问题。过去的分配,让无论是段错误或非法指令错误,阅读任何东西从阵列中说,中止陷阱(我不熟悉的那一个)。我知道这是有点学术,并会(希望)从来没有拿出在现实生活中,但有,在C标准说来治疗这类阵列任何特殊的方式,或者是它与编译器有所不同编译器?

This code will compile (and brings up no warnings with -Wall enabled), and it seems you can assign to testArray[0] without issue. Assigning past that gives either a segfault or illegal instruction error, and reading anything from the array says "Abort trap" (I'm not familiar with that one). I realize this is somewhat academic, and would (hopefully) never come up in real life, but is there any particular way that the C standard says to treat such arrays, or is does it vary from compiler to compiler?

推荐答案

这是不确定的行为,因为它打破了应当的约束:

It's undefined behaviour, because it breaks a "shall" constraint:

C99§6.7.5.2:

如果大小是前pression即
  不是一个整数常量前pression ...
  ......每次被评价应
  具有大于零的值。

If the size is an expression that is not an integer constant expression... ...each time it is evaluated it shall have a value greater than zero.

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

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