Remove errors from code of sparse matrix using linked list

Viewed 16

Not getting any error on running the code. On debugging Segmentation fault on if(j == temp->col) when j = 4

Create function "seems" to have created the function well but I'm unsure why the segmentation fault.

The matrix(5x6) I input was 0 0 0 0 0 1\n 1 0 0 0 0 1\n 1 1 0 0 0 1\n 1 1 1 1 0 0\n 0 0 0 0 1 1\n

The output I received was 0 0 0 0 0 1\n 1 0 0 0 0 1\n 1 1 0 0 0 1\n 1 1 1 1

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

struct node{
  int col;
  int data;
  struct node *next;
}*first;

void create(struct node *A[], int m, int n){
  struct node *temp, *last;
  int noe, flag = 0;
  for(int i = 0; i < m; i++){
    flag = 0;
    A[i] = (struct node *) malloc(sizeof(struct node));
    last = A[i];
    
    printf("Enter no. of items in Row %d :", i);
    scanf("%d", &noe);

    for(int j = 0; j < noe; j++){
      temp = (struct node *) malloc(sizeof(struct node));
      
      printf("Enter column and elmeent :");
      scanf("%d%d", &temp->col, &temp->data);
      
      temp->next = NULL;
      if(last == A[i] && flag == 0){
        A[i] = temp;
        flag = 1;
      }
      else
        last->next = temp;

      last = temp;

    }
    last = NULL;
  }
}

void display(struct node *A[], int m, int n){
  struct node *temp;
  for(int i = 0; i < m; i++){
    temp = A[i];
    for(int j = 0; j < n; j++){
      if(j == temp->col){
        printf("%d ", temp->data);
        temp = temp->next;
      }
      else
        printf("0 ");
    }
    printf("\n");
  }
}

int main(){
  
  int m = 5, n = 6;
  struct node *A[m];

  create(A, m, n);
  display(A, m, n);

  return 0;
}
0 Answers
Related