Alex Rivera | Logout

Declaring an array of negative length

Asked 2010-09-23T23:48:16.120
19

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?

Edit
Report

1 Answer

0

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.

answered 2010-09-24T00:00:15.900

Your Answer