Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions examples/dynamic_array.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* The size expression of a variable length array is evaluated exactly once,
* where the declaration is reached, and the address of a local declared after
* such an array does not depend on that size.
*/

int size()
{
printf("sizing array\n");
return 4;
}

void print_locals()
{
int n = 2;
int array[n];
int i;

i = 7;

/*
* Reassigning 'n' must not move 'i'. Its offset was fixed at compile time.
*/
n = 5;

printf("i=%d\n", i);
printf("n=%d\n", n);
}

void print_array()
{
/*
* "sizing array" is printed once, no matter how many times 'array' and
* 'total' are referenced below.
*/
int array[size()];
int total;
int i;

for (i=0; i<4; i++)
{
array[i] = i * 10;
}

total = 0;
for (i=0; i<4; i++)
{
total += array[i];
}

printf("total=%d\n", total);
}

int main()
{
print_locals();
print_array();
}
Loading