-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic_memory.c
More file actions
74 lines (57 loc) · 1.41 KB
/
dynamic_memory.c
File metadata and controls
74 lines (57 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define oops(s) {perror((s)); exit(EXIT_FAILURE);}
#define MALLOC(s, t) s = malloc(t); if(s == NULL) {oops("error: malloc() ");}
#define INCREMENT 10
int main() {
double x, y, z, **xyz, **tmp;
int i, scannedItems, current_size = 0, n = INCREMENT;
char buffer[50];
MALLOC(xyz, sizeof(double *) * INCREMENT);
for (i = 0; i < INCREMENT; i++) {
MALLOC(xyz[i], sizeof(double) * 3);
}
FILE *data = fopen("files/data", "r");
if (data == NULL) {
perror("Couldn't open file: ");
exit(EXIT_FAILURE);
}
tmp = xyz;
while (fgets(buffer, sizeof buffer, data) != NULL) {
scannedItems = sscanf(buffer, "%lf %lf %lf", &x, &y, &z);
if (scannedItems != 3) {
fprintf(stderr, "Invalid line: %s", buffer);
continue;
}
x = round(x * 100) / 100;
y = round(y * 100) / 100;
z = round(z * 100) / 100;
(*tmp)[0] = x;
(*tmp)[1] = y;
(*tmp)[2] = z;
current_size++;
if (current_size >= n) {
tmp = realloc(xyz, sizeof(double *) * (n + INCREMENT));
if (tmp == NULL) {
oops("realloc() error! ");
}
for (i = n; i < n + INCREMENT; i++) {
MALLOC(tmp[i], sizeof(double) * 3);
}
xyz = tmp;
tmp += (n-1);
n += INCREMENT;
}
tmp++;
}
fclose(data);
for (i = 0; i < n; i++) {
if (n < current_size) {
printf("%.2lf %.2lf %.2lf\n", xyz[i][0], xyz[i][1], xyz[i][2]);
}
free(xyz[i]);
}
free(xyz);
return EXIT_SUCCESS;
}