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.
More Pointers and Dynamic Memory practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!