-1

Here I just want to define a function which returns the multiplication of matrices, with N arbitrary, I would like to generate a matrix with "new" command.

int **multiply(int **A, int **B, int N){
   int **C=new int*[N];
   for(int i=0;i<N;i++){
   for(int j=0;j<N;j++){
       for(int k=0;k<N;k++)
       C[i][j]=C[i][j]+A[i][k]*B[k][j];
     }
   }
   return (C);
}

The output looks like

Segmentation fault (core dumped)

whenever I assign values to C I have this error, could anybody tell me what happened and how to fix it?

  • 2
    Check up on how to work with pointers. Also, this post belongs on SO. – Zeroth May 09 '14 at 22:12
  • Ummmm..... just an hour ago: http://stackoverflow.com/questions/23574807/segmentation-fault-error-occurs-for-a-simple-function-i-have-coded – chris May 10 '14 at 00:35

1 Answers1

0

int **C declares a pointer to a pointer, and since in C\C++ arrays are pointers, C is an array of arrays. new int*[N] creates the outer array, but it does not create the inner arrays. At no point do you create the inner arrays and assign them to the cells of C, so C[#] contains junk(if I recall correctly, 0 if you compile in debug mode and whatever was in that memory before if you use release mode). When you use C[i][j], since C[i] contains either 0 or junk you get a segfault.

int **multiply(int **A, int **B, int N){
    int **C=new int*[N];
    for(int i=0;i<N;i++){
        C[i]=new int[N]; // Create the inner array here
        for(int j=0;j<N;j++){
            C[i][j]=0; // You need to initialize the cell or else it'll contain some random junk
            for(int k=0;k<N;k++)
                C[i][j]=C[i][j]+A[i][k]*B[k][j];
        }
    }
    return (C);
} 
Idan Arye
  • 12,402
  • 5
  • 49
  • 68