Hey guys, I am new to data structures using C. I have been told to add two 2D arrays. I have taken the Row, Column and Value input of the non zero values from the user for the two sparse matrix and stored them dynamically in the memory pointed by the integer pointer 'a'(for the first one) and 'b'(for the second one). The problem I am facing is how do I add both these matrix and store them in another memory location pointed by 'c'. I want to do this operation without creating any kind of 2D array if possible(using linear memory location). Here is the code I created so far for taking input of the Row, Col and Non-Zero values of the two sparse matrix from the user and print the 2D sparse matrix from it:
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *a, *b, *c, row, col, val1, val2, ind1 = 0, ind2 = 0, ind3 = 0, ri1, ci1, ri2, ci2, count = 0;
printf("Please Enter The Rows In Sparse Matrix: ");
scanf("%d", &row);
printf("Please Enter The Cols In Sparse Matrix: ");
scanf("%d", &col);
printf("Please Enter The No. Of Non Zero Elements In First Matrix: ");
scanf("%d", &val1);
printf("Please Enter The No. Of Non Zero Elements In Second Matrix: ");
scanf("%d", &val2);
a = (int *)malloc(sizeof(int)*(val1+1)*3);
a[ind1++] = row; //store the total number of rows in actual matrix at a[o]
a[ind1++] = col; //store the total number of cols in actual matrix at a[1]
a[ind1++] = val1; //store the total number of non-zero values in actual matrix at a[2]
printf("Please Enter The Data For First Sparse Matrix: \n");
for(int i = 1; i <= val1; i++) {
printf("Enter Row %d: ", i);
scanf("%d", &a[ind1++]);
printf("Enter Col %d: ", i);
scanf("%d", &a[ind1++]);
printf("Enter Value %d: ", i);
scanf("%d", &a[ind1++]);
}
ind1 = 0;
b = (int *)malloc(sizeof(int)*(val2+1)*3);
b[ind1++] = row; //store the total number of rows in actual matrix at b[o]
b[ind1++] = col; //store the total number of cols in actual matrix at b[1]
b[ind1++] = val2; //store the total number of non-zero values in actual matrix at b[2]
printf("Please Enter The Data For Second Sparse Matrix: \n");
for(int i = 1; i <= val2; i++) {
printf("Enter Row %d: ", i);
scanf("%d", &b[ind1++]);
printf("Enter Col %d: ", i);
scanf("%d", &b[ind1++]);
printf("Enter Value %d: ", i);
scanf("%d", &b[ind1++]);
}
printf("The Entered Elements Of Matrix 1 Are: \n");
for(int i = 0; i < (val1+1)*3; i++)
printf("%d \t", a[i]);
printf("The Entered Elements Of Matrix 2 Are: \n");
for(int i = 0; i < (val2+1)*3; i++)
printf("%d \t", b[i]);
}
Any help will be appreciated..