从C中的结构数组中删除元素?

时间:2013-11-04 06:57:46

标签: c arrays struct

我是C的新手,老实说不知道从哪里开始从结构数组中删除特定元素。

如果您愿意,可以在此处查看和复制我的代码:http://pastebin.com/Zbrm2xyL

大多数情况下,我关注函数'rmv_student',它应该从数组'st_array'中删除带有匹配id号的结构,而不会在提示用户确认后弄乱该数组的其他元素。函数'rmv_student'如下:

void rmv_student(long id) // BROKEN
{
int i; // iterator
char response; // used to confirm deletion

for( i = 0; i < MAX; i++){
    if ( st_array[i].id == id){
        printf("Are you sure you want to delete %s %s, %d?\n", st_array[i].first_name, st_array[i].last_name, st_array[i].id);
        puts("You will not be able to undo the deletion.");
        puts("Enter 'y' to delete or 'n' to return to the main menu.");
        response = getchar();

        switch (response){

            case 'y':
                // delete

            case 'Y':
                // delete

            case 'n':
                main();

            case 'N':
                main();

            default:
                puts("Please enter 'y' or 'n'.");
                rmv_student(id);
        }
    }
}
if ( i == MAX ){
    printf("\nThere are no students with ID %d.\n\n", id);
    main();
}
}

我有两个问题。

  1. 我的开关盒是否正确?这会正确测试用户的输入字符吗?

  2. 如何删除结构?

  3. 在你问之前。是的,这是功课。因此,我不是在寻找讲义,只是朝着正确的方向前进。欢迎任何其他建议。

    注意:我知道我并不需要'menu_test_input'功能,但我现在暂时离开。

3 个答案:

答案 0 :(得分:1)

使用循环和返回语句而不是递归调用!请记住,当被调用函数返回时,代码将在调用后继续。

而是做类似下面的伪代码

do
{
    print_prompt()
    get_response()

} while (response is not legal)

if (response is yes)
    do_the_actual_deletion

如果要删除数组A的元素X,则将元素X + 1移动到X,将元素X + 2移动到X + 1等。完成后,将大小减小1。没有涉及实际的“删除”。

答案 1 :(得分:1)

您的问题有两种可能的解决方案,您应该使用哪种解决方案取决于数组元素的顺序对您是否重要。

  1. 快速解决方案:将数组中的最后一个元素复制到要删除的元素的位置,然后简单地减少数组中元素的数量。

    int* array = ...;
    int elementCount = ...;
    ...
    int deletionIndex = ...;
    array[deletionIndex] = array[--elementCount];    //the deletion is actually a one liner :-)
    

    无论何时使用未排序的数组操作,此解决方案都是首选解决方案,无论您在何处进行删除,它都只需要一段时间。

  2. 长解决方案:将已删除元素后面的所有元素移到前面一个位置。

    //setup is the same as for the fast solution
    elementCount--;
    for(int i = deletionIndex; i < elementCount; i++) array[i] = array[i+1];
    

    不是很困难,但比快速解决方案复杂得多。

    每当需要保留数组元素的相对顺序时,都需要使用它。排序的代价是运行时取决于需要移动的元素数量。

答案 2 :(得分:0)

你必须使用break;

case 'y':
//your code 
     break;
case 'Y':
//your code 
     break;
case 'n':
     break;
...
......

或代码将运行您的所有案例。

正确使用 - http://www.tutorialspoint.com/cprogramming/switch_statement_in_c.htm

相关问题