C programming/Variable Lengt Arrays VLA

From Teknologisk videncenter
< C programming
Revision as of 06:57, 1 December 2022 by Heth (talk | contribs) (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...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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);
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 }