Declaring an array of negative length

半腔热情 提交于 2019-11-27 04:07:20

问题


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

For instance:

int n = -35;

int testArray[n];

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

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?


回答1:


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

C99 §6.7.5.2:

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.




回答2:


Undefined behavior, I believe, though don't quote me on that.

This gives the error error: size of array 'testArray' is negative in gcc:

int testArray[-35];

though, as you've seen:

int n = -35;
int testArray[n];

does not give an error even with both -Wall and -W.

However, if you use -pedantic flag, gcc will warn that ISO C90 forbids variable length array.




回答3:


Visual studio erro message for compilation, you can use -1 to say an empty array. It expects int and you are passing int, so no compiler error.



来源:https://stackoverflow.com/questions/3783282/declaring-an-array-of-negative-length

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!