Answer the question
In order to leave comments, you need to log in
How to fix segmentation error in C?
I have a two-dimensional dynamic array, consisting, for example, of 2 rows and 3 columns:
1 2 3
4 5 6
The essence of the task: flip our original array by 90 degrees, that is, in our case, make an array of 3 rows and 2 columns:
4 1
5 2
6 3
#include <stdio.h>
#include <stdlib.h>
int main() {
int N, M;
int **array;
int **newArray;
printf("Введите числа N и M: ");
scanf("%d %d", &N, &M);
array = (int **)malloc(N * sizeof(int));
for (int i = 0; i < N; i++) {
array[i] = (int *)malloc(M * sizeof(int));
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
printf("array[%d][%d] = ", i, j);
scanf("%d", &array[i][j]);
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
printf("\n");
newArray = (int **)malloc(M * sizeof(int));
for (int i = 0; i < M; i++) {
newArray[i] = (int *)malloc(N * sizeof(int));
}
printf("%d %d \n", M, N);
for (int i = 0; i < M; i++) {
int n2 = N - 1;
for (int j = 0; j < N; j++) {
newArray[i][j] = array[n2][i];
printf("%d ", newArray[i][j]);
n2--;
}
printf("\n");
}
}
Answer the question
In order to leave comments, you need to log in
Mistake #1
array = (int **)malloc(N * sizeof(int));
newArray = (int **)malloc(M * sizeof(int));
Here you must allocate an array of pointers, not an array of ints. Those. should be
array = (int **)malloc(N * sizeof(int*));
newArray = (int **)malloc(M * sizeof(int*));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question