I wrote this code to implement sparse matrix using linked list but I don't why I am getting error(segmentation fault).....can somebody help me with that.
I created an array of linked list, the index of array represents row of matrix and in linked-list I am storing col and data value.
There is a link to a image below that may help you understand the code better.
https://i.sstatic.net/9rwH9.png
#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 *t, *last;
printf("Enter the elements of sparse matrix:\n");
for(int i=0; i<m; i++){
first = NULL;
last = NULL;
for(int j=0; j<n; j++){
int val;
scanf("%d", &val);
if(val != 0){
t= (struct Node *)malloc(sizeof(struct Node));
t->col = j;
t->data = val;
t->next = NULL;
if(first)
first = t;
if(last)
last->next = t;
last = t;
}
}
A[i] = first;
}
return;
}
void Display(struct Node **A, int m, int n){
printf("\nSparse matrix is:\n");
for(int i=0; i<m; i++){
struct Node *p = A[i];
for(int j=0; j<n; j++){
if(p->col == j){
printf(" %d ", p->data);
if(p)
p = p->next;
}
else printf(" 0 ");
}
printf("\n");
}
}
int main() {
int m=5, n=6;
struct Node **A = (struct Node **)malloc(m * sizeof(struct Node));
Create(A, m, n);
Display(A, m, n);
return 0;
}
There are three things to fix your code:
When you allocate, you should allocate space for the data type the handle to the memory points to, in your case a struct Node *
:
struct Node **A = malloc(m * sizeof(struct Node *));
You can write this as:
struct Node **A = malloc(m * sizeof(*A));
You should also free
all allocated data after using it. (The mis-allocation doesn't hurt here, because you allocate more than you need, but if you get the types wrong and allocate too little, you're in for surprises.)
When you insert the first node, head
is null, so that's the condition to check:
if (first == NULL)
first = t;
Your original code never adds any nodes to the list.
When you print, you access p
, but p
might be null. That's the very first thing you have to check before any access to p
:
if (p && p->col == j){
printf(" %d ", p->data);
p = p->next;
}