Note that there are some explanatory texts on larger screens.

plurals
  1. POCan a variable be used to define the size of an array on the stack in c?
    text
    copied!<p>I have a situation where I want my program to read in some numbers that will define the size of a two dimensional array (used as a matrix). I originally argued that the only way to do this would be to use a <code>malloc</code> call to put the array on the heap, something like this:</p> <pre><code>matrixElement* matrix = malloc(sizeof(matrixElement) * numRows * numCols); </code></pre> <p>where numCols and numRows are the integers which were read in earlier, and matrixElement is some arbitrary type. My reasoning was that simply writing:</p> <pre><code>matrixElement matrix[numRows][numCols]; </code></pre> <p>would not work since the compiler would have no way of knowing how much stack space to allocate to the function call. It turns out I was wrong, since the following code compiles and runs:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(void) { int x, y; scanf("%d", &amp;x); scanf("%d", &amp;y); double arr[x][y]; printf("Made an array of size %d by %d, total memory %fKb\n", sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]) / sizeof(arr[0][0]), (float) sizeof(arr) / 1024.0f); return 0; } </code></pre> <p>With big enough numbers input for x and y, this will eventually give a segfault, but I was very surprised too see that I could create a 1000x1000 array with this code. </p> <p>Can anyone explain what is going on here? </p> <p>Is the compiler just allocating a bunch of space for the array, even though it has no idea how much will be used? </p> <p>Is this behavior specified by ANSI C or is it just something that gcc is doing on its own?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload