-
Notifications
You must be signed in to change notification settings - Fork 0
/
assignment.c
94 lines (82 loc) · 2.37 KB
/
assignment.c
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
int main(int argc, char *argv[]) {
// initialize random number generator
srand(time(NULL));
int minrand = 1;
int maxrand = 100;
// WRITE YOUR CODE HERE
// Check the number of arguments
if (argc != 3) {
printf("Incorrect usage. You provided %d arguments. The correct number of arguments is 2\n", argc - 1);
return 1;
}
// Validate the arguments to ensure they are positive integers
char *endptr1, *endptr2;
errno = 0;
long rows = strtol(argv[1], &endptr1, 10);
long cols = strtol(argv[2], &endptr2, 10);
if (*endptr1 != '\0' || *endptr2 != '\0' || errno != 0 || rows <= 0 || cols <= 0) {
printf("Incorrect usage. The parameters you provided are not positive integers\n");
return 1;
}
// Allocate memory for the matrix
int **matrix = (int **)malloc(rows * sizeof(int *));
if (!matrix) {
perror("Memory allocation failed");
return 1;
}
for (int i = 0; i < rows; i++) {
matrix[i] = (int *)malloc(cols * sizeof(int));
if (!matrix[i]) {
perror("Memory allocation failed");
for (int j = 0; j < i; j++) {
free(matrix[j]);
}
free(matrix);
return 1;
}
}
// Fill the matrix with random numbers between 1 and 100
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = minrand + rand() % (maxrand - minrand + 1);
}
}
// Write the matrix to the file
FILE *file = fopen("matrix.txt", "w");
if (!file) {
perror("Failed to open the file");
for (int i = 0; i < rows; i++) {
free(matrix[i]);
}
free(matrix);
return 1;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
fprintf(file, "%d", matrix[i][j]);
if (j < cols - 1) {
fprintf(file, " ");
}
}
if (i < rows - 1) {
fprintf(file, "\n");
} else {
fprintf(file, "\r");
}
}
fclose(file);
// Free the allocated memory
for (int i = 0; i < rows; i++) {
free(matrix[i]);
}
free(matrix);
return 0;
}