Difference between revisions of "C programming/Variable Lengt Arrays VLA"
From Teknologisk videncenter
(Created page with "From C99 variable length arrays was introduced in c. <source lang=c line> #include <stdio.h> #include <stdlib.h> float process(int n, float *vals) { for (int i=0; i...") |
m |
||
Line 31: | Line 31: | ||
read_and_process_vla(10); | read_and_process_vla(10); | ||
read_and_process_vla(20); | read_and_process_vla(20); | ||
− | //read_and_process_vla(10000000); | + | //read_and_process_vla(10000000); // Error if stacksize not big enough... |
printf("======================= not using VLA =======================\n"); | printf("======================= not using VLA =======================\n"); | ||
read_and_process_novla(10); | read_and_process_novla(10); |
Revision as of 06:57, 1 December 2022
From C99 variable length arrays was introduced in c.
1 #include <stdio.h>
2 #include <stdlib.h>
3
4
5 float process(int n, float *vals) {
6 for (int i=0; i < n; i++) {
7 printf("%f ", vals[i]);
8 }
9 printf("\n");
10 }
11
12 float read_and_process_vla(int n) {
13 float vals[n];
14 for (int i = 0; i < n; ++i)
15 vals[i] = i;
16 return process(n, vals);
17 }
18
19 float read_and_process_novla(int n) {
20 float (*vals)[n] = malloc(sizeof(float[n]));
21 for (int i = 0; i < n; ++i)
22 (*vals)[i] = i;
23 float ret = process(n, *vals);
24 free(vals);
25 return ret;
26 }
27 int main(void) {
28 printf("========================= Using VLA =========================\n");
29 read_and_process_vla(10);
30 read_and_process_vla(20);
31 //read_and_process_vla(10000000); // Error if stacksize not big enough...
32 printf("======================= not using VLA =======================\n");
33 read_and_process_novla(10);
34 read_and_process_novla(20);
35 read_and_process_novla(10000000);
36 return(0);
37 }