I was trying to merge two stack into one but its show segmentaion error. i debugged the code and found error on line 41.
sp[2].arr[val] = sp[i].arr[j];
Heres the code:
#include <stdlib.h>
struct stack{
int size;
int top;
int *arr;
};
void push(struct stack *sp, int k)
{
int val;
for(int i=0;i<sp[k].size;i++)
{
if(sp[k].top == sp[k].size)
{
printf("Stack overflow\n");
}
else
{
sp[k].top++;
scanf("%d", &val);
sp[k].arr[sp[k].top] = val;
}
}
}
void merge(struct stack *sp)
{
int j=0,k=0;
//sp[2].size = sp[0].size + sp[1].size;
int val = 0;
for(int i=0;i<2;i++)
{
//k=k+sp[i].size;
for(j=0;j<sp[i].size;j++)
{
sp[2].arr[val] = sp[i].arr[j];
val++;
}
}
}
void display(struct stack *sp)
{
for(int i=0;i<2;i++)
{
for(int j=0;j<sp[i].size;j++)
{
printf("%d", sp[i].arr[j]);
}
}
}
int main(){
struct stack *sp = (struct stack *) malloc(3*sizeof(sp));
printf("Enter the size of first stack:\n");
scanf("%d", &sp[0].size);
printf("Enter the size of second stack:\n");
scanf("%d", &sp[1].size);
sp[2].size = sp[0].size + sp[1].size;
sp[0].arr = (int *) malloc(sp[0].size*sizeof(int));
sp[1].arr = (int *) malloc(sp[1].size*sizeof(int));
sp[2].arr = (int *) malloc(sp[2].size*sizeof(int));
sp[0].top = -1;
sp[1].top = -1;
sp[2].top = -1;
for(int i =0;i<2;i++)
{
printf("Enter the element of %d stack:\n", i+1);
push(sp,i);
}
merge(sp);
display(sp);
}