This problem is about adding two sparse matrix. At first I created two sparse matrix s1,s2 (taking the elements value manually) then adding them in sum. If I run it in code blocks I got an incorrect answer. But if I debug and run it, then the answer I got is perfect. This thing is happening again and again. I don't know why. Please give me a fruitful solution. Thank you
#include<bits/stdc++.h>
using namespace std;
struct Element
{
    int i;
    int j;
    int x;
};
struct Sparse_Matrix
{
    int m;
    int n;
    int num;
    struct Element *e;
};
void creation(struct Sparse_Matrix *s)
{
    cout<<"Enter dimension : ";
    cin>>s->m>>s->n;
    cout<<"Enter the number of nonzero elements : ";
    cin>>s->num;
    s->e=new Element[s->num+1];
    cout<<"Enter all non zero elements with it's location "<<endl;
    for(int p=1; p<=s->num; p++)
        cin>>s->e[p].i>>s->e[p].j>>s->e[p].x;
}
struct Sparse_Matrix *Addition(struct Sparse_Matrix *s1,struct Sparse_Matrix *s2)
{
    if((s1->m != s2->m) && (s1->n != s2->n))
        return 0;
    struct Sparse_Matrix *sum;
    sum=new Sparse_Matrix();
    sum->e=new Element[s1->num+s2->num+1];
    int i=0,j=0,k=0;
    while(i<=s1->num && j<=s1->num)
    {
        if(s1->e[i].i<s2->e[j].i)
            sum->e[k++]=s1->e[i++];
        else if(s1->e[i].i>s2->e[j].i)
            sum->e[k++]=s2->e[j++];
        else
        {
            if(s1->e[i].j<s2->e[j].j)
                sum->e[k++]=s1->e[i++];
            else if(s1->e[i].j>s2->e[j].j)
                sum->e[k++]=s2->e[j++];
            else
            {
                sum->e[k]=s1->e[i++];
                sum->e[k++].x+=s2->e[j++].x;
            }
        }
    }
    for(; i<=s1->num; i++)
        sum->e[k++]=s1->e[i++];
    for(; j<=s2->num; j++)
        sum->e[k++]=s2->e[j++];
    sum->n=k;
    sum->m=s1->m;
    sum->n=s1->n;
    return sum;
};
void display(struct Sparse_Matrix s)
{
    int k=1;
    for(int p=1; p<=s.m; p++)
    {
        for(int q=1; q<=s.n; q++)
        {
            if(s.e[k].i==p && s.e[k].j==q)
                cout<<s.e[k++].x<<" ";
            else
                cout<<"0 ";
        }
        cout<<endl;
    }
}
int main()
{
    struct Sparse_Matrix s1,s2,*sum;
    creation(&s1);
    creation(&s2);
    cout<<"Displaying the s1 Matrix "<<endl;
    display(s1);
    cout<<"Display the s2 Matrix "<<endl;
    display(s2);
    sum=Addition(&s1,&s2);
    cout<<"Displaying the sum "<<endl;
    display(*sum);
}
 
     
    