LearnFrenzy
Sign in Take a free test

Pointers and Dynamic Memory · Pointer Programs · Question 5

Dynamic matrix: read, transpose and free in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Read a rows × cols matrix into memory allocated with new, build its transpose in a second dynamic matrix, print it and free everything.

Solution
main.cpp
#include <iostream>

int** make(int r, int c) {
    int** m = new int*[r];
    for (int i = 0; i < r; ++i) m[i] = new int[c];
    return m;
}

void destroy(int** m, int r) {
    for (int i = 0; i < r; ++i) delete[] m[i];
    delete[] m;
}

int main() {
    int r, c;
    std::cin >> r >> c;
    int** a = make(r, c);
    for (int i = 0; i < r; ++i)
        for (int j = 0; j < c; ++j) std::cin >> a[i][j];

    int** t = make(c, r);
    for (int i = 0; i < r; ++i)
        for (int j = 0; j < c; ++j) t[j][i] = a[i][j];

    for (int i = 0; i < c; ++i) {
        for (int j = 0; j < r; ++j) std::cout << t[i][j] << ' ';
        std::cout << '\n';
    }
    destroy(a, r);
    destroy(t, c);
    return 0;
}

Output Verified by compiling and running

1 4 
2 5 
3 6

Helper functions keep allocation and release symmetric. The transpose has the dimensions swapped, and each matrix is destroyed with its own row count.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links