// Study56.cpp: определяет точку входа для консольного приложения. // CppStudio Level: Normal Task 15 Переписать все элементы двумерного массива в одномерный #include "stdafx.h" #include <iostream> #include <cstdlib> #include <iomanip> using namespace std; int main() { setlocale(LC_CTYPE, "rus"); int n, m; cout << "Введите количество строк матрицы: "; cin >> n; cout << "Введите количество столбцов матрицы: "; cin >> m; int** M = new int *[n]; for (int i = 0; i < m; i++) { M[i] = new int[m]; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { M[i][j] = rand() % 100; } } cout << "Вы ввели: " << endl; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << setw(3) << M[i][j] << " "; } cout << endl; } int *mas = new int[n*m]; for (int i = 0; i < n ; i++) { for (int j = 0; j < m; j++) { for (int k = 0; k < n*m; k++) { mas[k] = M[i][j]; break; } } } cout << "Запись матрицы в строку: " << endl; for (int i = 0; i < (n * m); i++) { cout << mas[i] << " "; } cout << endl; system("pause"); return 0; } 1 answer
When you declare a pointer to an array of pointers
int** M = new int *[n];thus, you say that this pointerMcontains the address of the beginning of the array of thennumber of pointers, i.e. There arenpointers in the array. Therefore it is:for (int i = 0; i <m; i ++) {M [i] = new int [m]; }
This is a gross error, because you are going to initialize not n pieces of pointers, but m . Replace with the correct option:
for (int i = 0; i < n; i++) { M[i] = new int[m]; } Then you write a cycle that can be called a disgrace
for (int i = 0; i < n ; i++) { for (int j = 0; j < m; j++) { for (int k = 0; k < n*m; k++) { mas[k] = M[i][j]; break; } } }
Here, each time you initialize mas[0] and stop the work of the nested loop, so replace with:
for (int i = 0; i < n ; i++) for (int j = 0; j < m; j++) mas[i * m + j] = M[i][j]; In principle, to write a matrix into a row, a one-dimensional array is not needed at all, so your int *mas completely unnecessary.
And finally, you allocate memory in a free area with the new operator, so you must free all of this memory at the end of the program:
for (int i = 0; i < n; i++) delete [] M[i]; delete [] mas;