Deleting an array element in C

后端 未结 7 1797
自闭症患者
自闭症患者 2021-01-06 14:51

I wrote the following program to delete an array element entered by the user.

#include 
#include 

void main() {
    int j, i,          


        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-06 15:16

    Other posters have given you 2 solutions ... I think understanding why it happens is good too :)

    Let's take your example 1, 2, 2, 3, 5 and follow the code line by line

    i = 0;             /* first time through the loop; i "points" to 1 */
    if (a[i] == 2) ... /* nope; next loop */
    i = 1;
    if (a[1] == 2) ... /* yes! let's go inside the if */
                       /* move all elements back
                       ** and "decrease" array length */
                       /* array is now 1, 2, 3, 5 */
                       /* next loop */
    i = 2;
    if (a[i] == 2) ... /* nope; OH! Wait ...
                       ** a[1] is the new 2 and it wasn't checked */
    

提交回复
热议问题