Основы программирования на С++ для начинающих

Задачи и решения: Указатель на указатель

1) Создать двумерный массив 5х5, заполнить его случайными числами от 10 до 99 и вывести на экран. Поменять местами максимальный элемент каждой строки с первым элементом в соответствующей строке. Задачу решить с помощью указателей.

2) Задача на умножение матриц. Пользователь произвольно задает размерность двух матриц и заполняет значениями вручную. Не забывайте, что необходимо выделить соответствующие участки памяти для матриц, которые будет заполнять пользователь и для третьей итоговой матрицы. Далее отобразите на экране обе заполненные матрицы и итоговую матрицу (их воспроизведение).

Возможно кто-то не знает, как умножать матрицы. Посмотрите это короткое видео (автор: Приходовский М.А.)

15 thoughts on “Задачи и решения: Указатель на указатель

  1. #include
    #include
    #include
    using namespace std;

    void logo()
    {
    cout << "+————————————————-+" << endl;
    cout << "|Программа для арифметических операций с матрицами|" << endl;
    cout << "+————————————————-+" << endl << endl;
    }

    void DeleateMatrix(int**& matrix, int rows, int cols)
    {
    for (int i = 0; i < rows; i++)
    {
    delete[] matrix[i];
    }
    delete[] matrix;
    matrix = nullptr;
    }

    void CreateMatrix(int **&matrix, int rows, int cols)
    {
    matrix = new int* [rows];
    for (int i = 0; i < rows; i++)
    {
    matrix[i] = new int[cols];
    }
    for (int i = 0; i < rows; i++)
    {
    for (int j = 0; j < cols; j++)
    {
    matrix[i][j] = 0;
    }
    }
    }

    void InputMatrix(int **&matrix, int rows, int cols)
    {
    for (int i = 0; i < rows; i++)
    {
    cout << i + 1 << " строка: " << endl;
    for (int j = 0; j < cols; j++)
    {
    cout <= k; k *= 10)
    {
    cout << " ";
    }
    cout << j + 1;
    cout <> matrix[i][j];
    }
    }
    }

    void OutputMatrix(int **& matrix, int rows, int cols)
    {
    cout << endl;
    for (int i = 0; i < rows; i++)
    {
    for (int j = 0; j < cols; j++)
    {
    if (j == 0)
    {
    cout << "{ ";
    }
    cout << matrix[i][j];
    if (j != cols – 1)
    {
    cout << "\t";
    }
    if (j == cols – 1)
    {
    cout << " }";
    }
    }
    cout << endl;
    }
    cout << endl;
    }
    int main()
    {
    setlocale(LC_ALL, "rus");
    while (true)
    {
    bool pause = 0;
    bool error = false;
    char repeat = 0;

    int** firstMatrix = 0;
    int firstRows = 0;
    int firstCols = 0;
    int** resultMatrix = 0;
    int** secondMatrix = 0;
    int secondRows = 0;
    int secondCols = 0;
    do {
    system("cls");
    logo();
    error = false;
    cout <> firstRows;
    cout <> firstCols;
    CreateMatrix(firstMatrix, firstRows, firstCols);
    cout << endl;
    cout <> secondRows;
    cout <> secondCols;
    CreateMatrix(secondMatrix, secondRows, secondCols);

    if (firstCols != secondRows)
    {
    cout << "\n\aОщибка! Количество столбцов в первом матрице не равно количеству строк во второй матрице(нажмите любую клавишу чтобы продолжить)" << endl;
    pause = _getch();
    error = true;
    }
    else if (repeat == 'R' || repeat == 'r' || repeat == 'К' || repeat == 'к')
    {
    cout << "\nПроверьте правильно ли вы ввели параметры матрицы." << endl
    << "Если вы неправильно ввели параметры, то нажмите клавишу R для того, чтобы ввести параметры снова" << endl
    << "(нажмите любую клавишу чтобы продлжить)" << endl;
    repeat = _getch();
    error = true;
    }

    if (firstRows == 0 || firstCols == 0 || secondRows == 0 || secondCols == 0)
    {
    cout << "\n\aОщибка! Количество строк или столбцов не может быть равно нулю(нажмите любую клавишу чтобы продолжить)" << endl;
    pause = _getch();
    error = true;
    }
    } while (error);
    do {
    error = false;
    system("cls");
    logo();
    cout << "\nЗаполните первую матрицу" << endl;
    InputMatrix(firstMatrix, firstRows, firstCols);
    OutputMatrix(firstMatrix, firstRows, firstCols);
    cout << "\nПроверьте правильно ли вы ввели данные в матрицу." << endl
    << "Если вы неправильно ввели данные, то нажмите клавишу R для того, чтобы ввести данные снова" << endl
    << "(нажмите любую клавишу чтобы продлжить)" << endl;
    repeat = _getch();
    if (repeat == 'R' || repeat == 'r' || repeat == 'К' || repeat == 'к')
    {
    error = true;
    }
    } while (error);
    do {
    error = false;
    system("cls");
    logo();
    cout << "Первая матрица: " << endl;
    OutputMatrix(firstMatrix, firstRows, firstCols);
    cout << "Заполните вторую матрицу" << endl;
    InputMatrix(secondMatrix, secondRows, secondCols);
    OutputMatrix(secondMatrix, secondRows, secondCols);
    cout << "\nПроверьте правильно ли вы ввели данные в матрицу." << endl
    << "Если вы неправильно ввели данные, то нажмите клавишу R для того, чтобы ввести данные снова" << endl
    << "(нажмите любую клавишу чтобы продлжить)" << endl;
    repeat = _getch();

    if (repeat == 'R' || repeat == 'r' || repeat == 'К' || repeat == 'к')
    {
    error = true;
    }
    } while (error);

    do {
    error = false;
    system("cls");
    logo();
    cout << "Первая матрица: " << endl;
    OutputMatrix(firstMatrix, firstRows, firstCols);
    cout << "Вторая матрица: " << endl;
    OutputMatrix(secondMatrix, secondRows, secondCols);
    cout << "Выберите арифметическую операцию, которую вы хотите выполнить с этими матрицами" << endl << endl;
    cout << "1. Умножение(количество строк в первой матрие должно быть равно количеству столбцов во второй матрице)" << endl;
    cout << "2. Сложение(матрицы должны быть одинакового размера)" << endl;
    cout << "3. Вычитание(матрицы должны быть одинакового размера)" << endl;
    CreateMatrix(resultMatrix, firstRows, secondCols);
    char choice = _getch();
    system("cls");
    logo();
    cout << "Первая матрица: " << endl;
    OutputMatrix(firstMatrix, firstRows, firstCols);
    cout << "Вторая матрица: " << endl;
    OutputMatrix(secondMatrix, secondRows, secondCols);
    switch (choice)
    {
    case '1':
    for (int i = 0; i < firstRows; i++)
    {
    for (int l = 0; l < secondCols; l++)
    {
    for (int j = 0; j < firstCols; j++)
    {
    resultMatrix[i][l] += firstMatrix[i][j] * secondMatrix[j][l];
    }
    }
    }
    cout << "Результат умножения двух матриц: " << endl;
    break;
    case '2':
    if (firstRows != secondRows && firstCols != secondCols)
    {
    cout << "Ощибка! Матрицы должны быть одинакового размера(нажмите любую клавишу чтобы продолжить)" << endl;
    }
    else
    {
    for (int i = 0; i < firstRows; i++)
    {
    for (int j = 0; j < firstCols; j++)
    {
    resultMatrix[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
    }
    }
    cout << "Результат сложения двух матриц: " << endl;
    }
    break;
    case '3':
    if (firstRows != secondRows && firstCols != secondCols)
    {
    cout << "Ощибка! Матрицы должны быть одинакового размера(нажмите любую клавишу чтобы продолжить)" << endl;
    }
    else
    {
    for (int i = 0; i < firstRows; i++)
    {
    for (int j = 0; j < firstCols; j++)
    {
    resultMatrix[i][j] = firstMatrix[i][j] – secondMatrix[i][j];
    }
    }
    cout << "Результат вычитания двух матриц: " << endl;
    }
    break;
    }
    OutputMatrix(resultMatrix, firstRows, secondCols);
    } while (error);
    DeleateMatrix(firstMatrix, firstRows, firstCols);
    DeleateMatrix(secondMatrix, secondRows, secondCols);
    DeleateMatrix(resultMatrix, firstRows, secondCols);
    cout << "Нажмите любую клавишу чтобы продолжить" << endl; _getch();
    }
    return 0;

  2. Кто-нибудь может подсказать, почему если int maxRowValue = arr[i][0],
    выдает ошибку?

    #include <iostream>
    using namespace std;

    int main()
    {
    int size = 5;

    int** arr = new int *[size];

    for (int i = 0; i < size; i++)
    {
    arr[i] = new int[size];
    }

    for (int i = 0; i < size; i++)
    {
    for (int j = 0; j < size; j++)
    {
    arr[i][j] = 10 + rand() % + 89;
    cout << arr[i][j] << "\t";
    }

    cout << endl;
    }

    cout << endl;

    for (int i = 0; i < size; i++)
    {
    int maxRowValue = 0; /*arr[i][0];*/
    int *buf = 0;

    for (int j = 0; j < size; j++)
    {
    if (arr[i][j] > maxRowValue)
    {
    maxRowValue = arr[i][j];
    buf = &(arr[i][j]);
    }
    }

    *buf = arr[i][0];
    arr[i][0] = maxRowValue;
    }

    for (int i = 0; i < size; i++)
    {
    for (int j = 0; j < size; j++)
    {
    cout << arr[i][j] << "\t";
    }

    cout << endl;
    }

    for (int i = 0; i < size; i++)
    {
    delete[] arr[i];
    } delete[]arr;
    }

    1. #include <iostream>
      using namespace std;

      int main()
      {
      int size = 5;

      int** arr = new int *[size];

      for (int i = 0; i < size; i++)
      {
      arr[i] = new int[size];
      }

      for (int i = 0; i < size; i++)
      {
      for (int j = 0; j < size; j++)
      {
      arr[i][j] = 10 + rand() % + 89;
      cout << arr[i][j] << "\t";
      }

      cout << endl;
      }

      cout << endl;

      for (int i = 0; i < size; i++)
      {
      int maxRowValue = 0; /*arr[i][0];*/
      int *buf = 0;

      for (int j = 0; j < size; j++)
      {
      if (arr[i][j] > maxRowValue)
      {
      maxRowValue = arr[i][j];
      buf = &(arr[i][j]);
      }
      }

      *buf = arr[i][0];
      arr[i][0] = maxRowValue;
      }

      for (int i = 0; i < size; i++)
      {
      for (int j = 0; j < size; j++)
      {
      cout << arr[i][j] << "\t";
      }

      cout << endl;
      }

      for (int i = 0; i < size; i++)
      {
      delete[] arr[i];
      } delete[]arr;
      }

  3. #include
    #include
    #include
    using namespace std;

    int main (){
    const int SIZE = 5;
    srand(time(NULL));
    int arr[SIZE][SIZE];
    for(int i=0;i<SIZE;i++){
    for (int j = 0; j < SIZE; j++){
    arr[i][j]= 10 + rand() % 90;
    }
    }
    for(int i=0;i<SIZE;i++){
    for (int j = 0; j < SIZE; j++){
    cout << arr[i][j] << '\t';}
    cout << endl;}
    for(int i=0;i<SIZE;i++){
    int j,k;
    int *max;
    max = &arr[i][0];
    int **first;
    first = &max;
    for( j=0;j *max){
    max=&arr[i][j];}}
    k = **first;
    *max = arr[i][0];
    arr[i][0] = k;
    }
    cout << endl << endl << endl;
    for(int i=0;i<SIZE;i++){
    for (int j = 0; j < SIZE; j++){
    cout << arr[i][j] << '\t';}
    cout << endl;}

    return 0;
    }

  4. Только заполняется сама, #ЖизниЛентяевВажны
    #include
    #include

    int main()
    {
    setlocale(LC_ALL, “rus”);
    srand(time(NULL));

    int rows1 = 0;
    int both = 0;
    int cols2 = 0;

    std::cout <> rows1;
    std::cout <> both;
    std::cout <> cols2;

    int** dArray1 = new int* [rows1]; // Выделение памяти для первой матрицы
    for (int i = 0; i < rows1; i++)
    {
    dArray1[i] = new int[both];
    }

    int** dArray2 = new int* [both]; // Выделение памяти для второй матрицы
    for (int i = 0; i < both; i++)
    {
    dArray2[i] = new int[cols2];
    }

    int** dArray3 = new int* [rows1]; // Выделение памяти для третьей матрицы
    for (int i = 0; i < rows1; i++)
    {
    dArray3[i] = new int[cols2];
    }

    for (int i = 0; i < rows1; i++) // Заполнение первой матрицы цифрами от 1 до 9
    {
    for (int j = 0; j < both; j++)
    {
    dArray1[i][j] = 1 + rand() % 9;
    }
    }
    for (int i = 0; i < rows1; i++) // Вывод первой матрицы
    {
    for (int j = 0; j < both; j++)
    {
    std::cout << dArray1[i][j] << " | ";
    }
    std::cout << "\n";
    }
    std::cout << "\n\n\n";

    for (int i = 0; i < both; i++) // Заполнение второй матрицы цифрами от 1 до 9
    {
    for (int j = 0; j < cols2; j++)
    {
    dArray2[i][j] = 1 + rand() % 9;
    }
    }
    for (int i = 0; i < both; i++) // Вывод второй матрицы
    {
    for (int j = 0; j < cols2; j++)
    {
    std::cout << dArray2[i][j] << " | ";
    }
    std::cout << "\n";
    }
    std::cout << "\n\n\n";

    for (int i = 0; i < rows1; i++)
    {
    for (int j = 0; j < cols2; j++)
    {
    int buffer = 0;

    for (int c = 0; c < both; c++)
    {
    buffer += dArray1[i][c] * dArray2[c][j];
    }
    dArray3[i][j] = buffer;
    }
    }

    for (int i = 0; i < rows1; i++)
    {
    for (int j = 0; j < cols2; j++)
    {
    std::cout << dArray3[i][j] << " | ";
    }
    std::cout << "\n";
    }

    for (int i = 0; i < rows1; i++) {
    delete[] dArray1[i];
    }
    delete[] dArray1;

    for (int i = 0; i < both; i++) {
    delete[] dArray2[i];
    }
    delete[] dArray2;

    for (int i = 0; i < rows1; i++) {
    delete[] dArray3[i];
    }
    delete[] dArray3;

    return 0;
    }

Добавить комментарий для Иван Отменить ответ

Ваш e-mail не будет опубликован. Обязательные поля помечены *