【问题标题】:How to delete a field from an array using pointers?如何使用指针从数组中删除字段?
【发布时间】:2015-03-05 12:10:43
【问题描述】:

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

/*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 变量吗?或者至少检查NULL 指针。
  • 您的错误主要是针对这一行 if ( posi &gt;= MAX_NUMB+1 ) 当您执行此操作时 for(c=posi;c&lt;MAX_NUMB;c++) else 部分。
  • @JoachimPileborg,谢谢,插入 student_numb——解决了问题。

标签: c linux menu


【解决方案1】:

假设 student_numb 是一个全局变量,当您成功删除一个条目时,您应该减少 student_numb 全局变量。删除函数见下面代码sn-p:

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--;**
  } 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多