'Program crashing while deleting an element. Other two cases are working perfectly
#include<stdio.h>
int main()
{
int i,n,roll,ch;
char name[20];
struct student
{
int roll;
char name[20];
}*ptr,*temp;
printf("Enter the number of students:");
scanf("%d",&n);
ptr=(struct student*)malloc(n*sizeof(struct student));
for(i=0;i<n;i++)
{
printf("Enter the roll number:");
scanf("%d",&ptr[i].roll);
printf("Enter the name:");
scanf("%s",ptr[i].name);
}
while(ch!=4){
printf("\n1.Insert\n2.Delete\n3.Display\n4.Exit");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter the roll number:");
scanf("%d",&roll);
printf("Enter the name:");
scanf("%s",name);
temp=(struct student*)malloc(n*sizeof(struct student));
for(i=0;i<n;i++)
{
temp[i].roll=ptr[i].roll;
strcpy(temp[i].name,ptr[i].name);
}
temp[n].roll=roll;
strcpy(temp[n].name,name);
free(ptr);
ptr=temp;
n++;
for(i=0;i<n;i++)
{
printf("%d %s\n",ptr[i].roll,ptr[i].name);
}
break;
case 2:
printf("Enter the roll number:");
scanf("%d",&roll);
temp=(struct student*)malloc(n*sizeof(struct student));
for(i=0;i<n;i++)
{
if(ptr[i].roll==roll)
{
i++;
}
temp[i-1].roll=ptr[i].roll;
strcpy(temp[i-1].name,ptr[i].name);
}
free(ptr);
ptr=temp;
n--;
for(i=0;i<n;i++)
{
printf("%d %s\n",ptr[i].roll,ptr[i].name);
}
break;
case 3:
for(i=0;i<n;i++)
{
printf("%d %s\n",ptr[i].roll,ptr[i].name);
}
break;
}
}
return 0;
}
The error message which I am getting-
Enter the number of students:2
Enter the roll number:87
Enter the name:Arya
Enter the roll number:45
Enter the name:Yo
1.Insert
2.Delete
3.Display
4.ExitEnter your choice:3
87 Arya
45 Yo
1.Insert
2.Delete
3.Display
4.ExitEnter your choice:1
Enter the roll number:88
Enter the name:Nair
87 Arya
45 Yo
88 Nair
1.Insert
2.Delete
3.Display
4.ExitEnter your choice:2
Enter the roll number:88
Process returned -1073741819 (0xC0000005) execution time : 45.341 s
Press any key to continue.
What am I doing wrong in the second case? Earlier I was trying to write the code by using double pointers but I was not able to implement it.
in case 2 my logic was to create a new temporary array and store all the elements other than the one with that "roll". i reviewed the code again and again and even asked my peers
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
