Systemnahe Programmierung in C: Dynamische Allokation von Feldern |
1#include <stdio.h>
2#include <stdlib.h>
3#include <errno.h>
4
5typedef unsigned long int Nat0;
6
7#define formatNat0 "%lu"
8
9int *
10mkField (Nat0 len)
11{
12 int *res = malloc (len * sizeof (int));
13
14 if (!res)
15 {
16 perror ("mkField: can't allocate field");
17 exit (1);
18 }
19
20 {
21 Nat0 i;
22 for (i = 0; i < len; ++i)
23 res[i] = 1;
24 }
25
26 return res;
27}
28
29int *
30sieveField (int field[], Nat0 len)
31{
32 Nat0 i;
33
34 field[0] = 0;
35 field[1] = 0;
36
37 for (i = 2; i < len; ++i)
38 if (field[i])
39 {
40 Nat0 j;
41 for (j = 2 * i; j < len; j += i)
42 field[j] = 0;
43 }
44
45 return field;
46}
47
48void
49writeField (int field[], Nat0 len)
50{
51 Nat0 i;
52 for (i = 0; i < len; ++i)
53 if (field[i])
54 printf (formatNat0 "\n", i);
55}
56
57int
58main (int argc, char *argv[])
59{
60
61 Nat0 len;
62 int *field;
63
64 sscanf (argv[1], formatNat0, &len);
65 field = mkField (len);
66
67 writeField (sieveField (field, len), len);
68
69 free (field);
70
71 return 0;
72}
|
|
Letzte Änderung: 22.11.2012 | © Prof. Dr. Uwe Schmidt |