gpt4 book ai didi

c - 如何使用指针从数组中删除字段?

转载 作者:行者123 更新时间:2023-11-30 17:19:33 25 4
gpt4 key购买 nike

这是我的菜单驱动程序的代码的一部分。每当我尝试删除一个字段时,它都会被删除,但我收到段错误(核心转储)错误。例如:如果我的记录列表是:

/*Student Name [0]: x
Student age [0] :1
Student Name [1]: y
Student age [1] :2
Student Name [2]: z
Student age [2] :3
Student Name [3]: f
Student age [3] :4*/

我在使用 printf 打印新列表后删除了记录 1 变为:

/*Student Name [0]: x
Student age [0] :1
Student Name [1]: z
Student age [1] :3
Student Name [2]: f
Student age [2] :4
Student Name [3]: ( null )
Segmentation fault (core dumped)

and exits the program.*/


int delete_posi ()
{
int posi;
int c=0;
int i;
printf("Enter the position to delete element:\n");
scanf("%d",&posi);
if ( posi >= MAX_NUMB+1 )
printf("Deletion not possible.\n");

else
{
for(c=posi;c<MAX_NUMB;c++)
ptr[c]=ptr[c+1],
ptr[c+1]=NULL;

}
}
//printing records , the struct contains Name,age
int printlist()
{
int i;
if(student_numb==0)
{
printf("List is empty\n");
}
for (i=0;i<student_numb;i++)
{
printf("*********************************\n");
printf("Student Name [%d] : %s\n",i, ptr[i]->Name);
printf("Student Age [%d] : %d\n",i, ptr[i]->age);
}
}

最佳答案

假设student_numb是一个全局变量,每当你成功删除一个条目时,你应该减少student_numb全局变量。请参阅以下删除功能的代码片段:

if( posi >= MAX_NUMB+1)
printf("Deletion..\n");
else
{
for(c=posi;c<MAX_NUMB;c++)
ptr[c]=ptr[c+1],
ptr[c+1]=NULL;
**student_numb--;**
}

关于c - 如何使用指针从数组中删除字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28877580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com