-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssignment01.c
More file actions
113 lines (97 loc) · 2.81 KB
/
Assignment01.c
File metadata and controls
113 lines (97 loc) · 2.81 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <stdio.h>
#include <stdlib.h>
#define N 5
#define M 6
void matrixArrayOfArrays(int n, int m);
void matrixOneBigArray(int n, int m);
int main(int argc,char** argv){
matrixArrayOfArrays(N,M);
matrixOneBigArray(N,M);
return 0;
}
void matrixArrayOfArrays(int n, int m) {
// Allocate memory for an array of pointers to float arrays
float **arr = (float **)malloc(m * sizeof(float *));
if (arr == NULL) {
printf("Error: Could not allocate memory.\n");
return;
}
// Allocate memory for each float array
for (int i = 0; i < m; i++) {
arr[i] = (float *)malloc(n * sizeof(float));
if (arr[i] == NULL) {
printf("Error: Could not allocate memory.\n");
// Free memory for previously allocated float arrays
for (int j = 0; j < i; j++) {
free(arr[j]);
}
// Free memory for the array of pointers
free(arr);
return;
}
}
// Fill the array with numbers
int num = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = num++;
}
}
// Print the array as a matrix
printf("Array:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%.0f\t", arr[i][j]);
}
printf("\n");
}
// Print the array transposed
printf("Array transposed:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%.0f\t", arr[j][i]);
}
printf("\n");
}
// Free memory for float arrays
for (int i = 0; i < m; i++) {
free(arr[i]);
}
// Free memory for the array of pointers
free(arr);
}
void matrixOneBigArray(int n, int m) {
float** matrix = (float**) malloc(m * sizeof(float*));
float* data = (float*) malloc(n * m * sizeof(float));
// Set each pointer in matrix to the corresponding row in data
for (int i = 0; i < m; i++) {
matrix[i] = &data[i * n];
}
// Fill the array with numbers 1 to n*m
int count = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = count;
count++;
}
}
// Print the matrix
printf("Matrix:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%-8.2f ", matrix[i][j]);
}
printf("\n");
}
// Print the matrix transposed
printf("Transposed matrix:\n");
for (int j = 0; j < n; j++) {
for (int i = 0; i < m; i++) {
printf("%-8.2f ", matrix[i][j]);
}
printf("\n");
}
// Deallocate memory
free(matrix);
free(data);
}