| Код | void reallocMatrix (Matrix *a, int m, int n);
|
Изменяет размеры матрицы a так, чтобы у неё было m строк и n столбцов. Лишние столбцы и строки удаляются, новые столбцы или строки добавляют- ся в конец. Новые строки и столбцы инициализировать нулями. Пример. Исходная матрица: 1 2 3 4 5 6 Вызов: reallocMatrix(a, 2, 4); Результат: 1 2 0 0 3 4 0 0 Вот код на си без этой функции и мейна. | Код | #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h>
typedef struct Matrix { int *data; int m, n; } Matrix;
void* mymalloc (size_t size); void* myrealloc (void *ptr, size_t size);
Matrix* newMatrix (int m, int n);
Matrix* copyMatrix (const Matrix *matrix);
void destroyMatrix (Matrix *matrix);
Matrix* readMatrix (const char *str);
void pprintMatrix (const Matrix *matrix);
void* myrealloc (void *ptr, size_t size) { void *res = realloc(ptr, size); if (res == NULL && size != 0) { fprintf(stderr, " \n", size); exit(EXIT_FAILURE); } return res; }
void* mymalloc (size_t size) { void *res = malloc(size); if (res == NULL) { fprintf(stderr, "mymalloc: неспособен выделять %zd байты\n ", size); exit(EXIT_FAILURE); } return res; }
Matrix* newMatrix(int m, int n) { Matrix * new_matrix = (Matrix *)mymalloc(sizeof(Matrix)); new_matrix -> m = m; new_matrix -> n = n; new_matrix -> data = (int *)mymalloc(n*m*sizeof(int)); return new_matrix; }
Matrix* copyMatrix(const Matrix *matrix) { Matrix* copy = newMatrix(matrix -> m, matrix -> n); for (int i = 0; i < matrix -> m * matrix -> n; i++) { copy -> data[i] = matrix -> data[i]; } return copy; }
void destroyMatrix (Matrix *matrix){ free(matrix->data); free(matrix); }
Matrix* readMatrix (const char *str) {
Matrix *matrix = NULL;
int m, n;
printf("Введите количество столбцов и строк для %s через пробел: ", str);
if (scanf("%d %d", &m, &n) != 2 || m < 0 || n < 0) goto fail;
matrix = newMatrix(m, n);
int *data = matrix->data;
int len = m * n;
for (int i = 0; i < len; i++) {
if (scanf("%d", data + i) != 1) goto fail;
}
return matrix;
fail:
fprintf(stderr, "readMatrix: ошибка при чтениии %s\n", str);
destroyMatrix(matrix);
return NULL;
}
void pprintMatrix (const Matrix *matrix) { int *data = matrix->data; int m = matrix->m, n = matrix->n; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { printf(" %4d", *data); data++; } printf("\n"); } }
void reallocMatrix (Matrix *a, int m, int n) {
|
Это сообщение отредактировал(а) kingler - 24.6.2016, 15:46
|