0

I have a 2d array I want to transpose and return from a function. Below is my code and I get the following error

#include <iostream>
#include <bits/stdc++.h>
#include <chrono>
#include <fstream>

using namespace std;

#define R 550 // ROWS
#define C 550 // COLS

void generate_matrix(double (*mat)[C], int n) {
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            mat[i][j] = rand() % 100;
        }
    } 
}

void print_matrix(double (*mat)[C], int n) {
    printf("Printing Matrix:\n ");
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            cout << mat[i][j] <<" ";
        }
    }
}

void initialize_matrix(double (*mat)[C], int n) {
    for (int i=0; i<n; i++) {
        for (int j=0; j<n; j++) {
            mat[i][j] = 0.0;
        }
    }
}


double** transpose_matrix(double (*mat)[C]) {  // problem is here
    double transpose[R][C];
    for (int i = 0; i < R; ++i) {
        for (int j = 0; j < R; ++j) {
         transpose[j][i] = mat[i][j];
      }
    }
    return transpose; // problem is here
      
}

int main() {
    double A[R][C], B[R][C], result[R][C];
    generate_matrix(A, C);
    generate_matrix(B, C);
    double** transposed_B = transpose_matrix(B);
    print_matrix(transposed_B);

}

Error Message:

mat_mul_transpose.cpp: In function ‘double** transpose_matrix(double (*)[550])’:
mat_mul_transpose.cpp:46:12: error: cannot convert ‘double (*)[550]’ to ‘double**’ in return
     return transpose;

How to fix this error?

Surya Tej
  • 1,342
  • 2
  • 15
  • 25
  • 2
    Two problems: a `double[R][C]` is **not** a pointer to a pointer (and can't decay to one), and there are many duplicates here about why you shouldn't try to return a pointer to a local variable that's about to be destroyed. Some similar questions are [Return a 2d array from a function](https://stackoverflow.com/questions/8617683/return-a-2d-array-from-a-function) and [Returning multidimensional array from function](https://stackoverflow.com/questions/3716595/returning-multidimensional-array-from-function), – Drew Dormann Feb 07 '22 at 01:35
  • 1
    Not only that, `double transpose[R][C];` will more than likely blow out the stack memory, since it is (assuming `sizeof(double) == 8`) over 2 megabytes of stack memory. You make the same issue in `main`, where you have 3 such arrays, totalling more than 6 MB of memory on the stack. – PaulMcKenzie Feb 07 '22 at 01:43
  • 1
    Don't use raw arrays. Always use `std::vector` instead or, if you really have a need for fixed-size arrays, `std::array`. Then all of this would be much more straight-forward. – user17732522 Feb 07 '22 at 01:46

0 Answers0