0

Using C, I want to transpose normal Matrix to Sparse Matrix what's wrong with this?

#include <stdio.h>
#include <stdlib.h>

int i;
int j;

int size1;
int size2;

int **mat1;
int **mat2;
int **sparseMat1;
int **sparseMat2;
int **tempMat;

void newMatrix(int **matrix, int n);
    
void moveToSparse(int **matrix, int** sparseMat, int size);

Just randomize a size of n x n matrix, create, and make it to sparsematrix

int main(void){
    size1 = rand() % 10 + 10;
    size2 = rand() % 10 + 10;
    newMatrix(mat1, size1);
    newMatrix(mat2, size2);
    moveToSparse(mat1, sparseMat1, size1);
    moveToSparse(mat2, sparseMat2, size2);

}

This part is to create a new n,n Matrix

void newMatrix(int** matrix, int n) {
    matrix = (int**)malloc(n * sizeof(int*));
    for (i = 0; i < n; i++) {
        matrix[i] = (int*)malloc(sizeof(int) * n);
    }

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            matrix[i][j] = rand() % 100;
        }
    }
}

This part is to transe normal matrix to sparse matrix

void moveToSparse(int** matrix, int **sparseMat,int n) {
    int k = 1;

    sparseMat = (int**)malloc(n * sizeof(int*));
    for (i = 0; i < 3; i++) {
        sparseMat[i] = (int*)malloc(sizeof(int) * 3);
    }

    sparseMat[0][0] = n;
    sparseMat[0][1] = n;

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            if (matrix[i][j]>0) {
                sparseMat[k][0] = i;
                sparseMat[k][1] = j;
                sparseMat[k][2] = matrix[i][j];
                k++;
            }
        }
    }

    sparseMat[0][2] = k;

}

I thought it can't read Matrix[i][j] but I can't catch what is wrong.

Gerhard
  • 6,850
  • 8
  • 51
  • 81
  • 1
    `matrix = (int**)malloc(n * sizeof(int*));` means *nothing* to the caller of `newMatrix`. That is value-assigning to an automatic variable. The caller's provided pointers are ultimately unchanged, the function leaks memory, etc. If you *debug* your program you'll see `mat1` and `mat2` are unchanged after calling `newMatrix`. There are *hundreds* of duplicates of this logic problem on this site; hopefully someone has one on a short-list to link. (and yes, `moveToSparse` has the exact same issue with `sparseMat`). – WhozCraig Sep 07 '21 at 08:30
  • This is a common bug, please study the linked duplicate. – Lundin Sep 07 '21 at 08:41
  • I'll try a shot on this. Thanks guys – emptyinteger Sep 07 '21 at 09:00

0 Answers0