简体   繁体   English

从数组中删除一个元素

[英]deleting an element from array

I was trying to delete an element from an array, I have succeeded, but I got unknown numbers (0 1804185664) after deleting an element from array.我试图从数组中删除一个元素,我成功了,但是从数组中删除一个元素后我得到了未知数(0 1804185664)。

Can someone help me out why did that appear?有人可以帮我看看为什么会出现吗?

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int arr[30];
    int n,i,pos;
    
    printf("how many ele\n");
    scanf("%d", &n);
    printf("enter %d ele\n",n);
    for(i=0;i<n;i++)
    {
      scanf("%d", &a[i]);
    }
    
    printf("enter position of element to be deleted\n");
    scanf("%d", &pos);
    for(i=pos-1; i<=n;i++)
    {
      a[i]= a[i+1];
    }
    printf("elements in array are\n");
    for(i=0; i<=n;i++)
    {
      printf("%d\t", a[i]);
    }
    return 0;
}

Output: Output:

how many ele
7
enter 7 ele
1
5
34
6
23
78
5
enter position of element to be deleted
3
elements in array are
1   5   6   23  78  5   0   1804185664  

I modified your code, and as they were saying in the comments for your question, the problem is that you were accessing elements outside you array range, also there is one more thing with you code is the what if you want to delete the last element in the array, how would you delete it?我修改了你的代码,正如他们在你的问题的评论中所说的那样,问题是你正在访问数组范围之外的元素,你的代码还有一件事是如果你想删除最后一个元素在数组中,你将如何删除它? , instead of shifting all elements of the array, you can put the maximum/minimum value of integer in the place you are deleting so that you come back to that place, you will know this place was deleted before. ,而不是移动数组的所有元素,你可以把 integer 的最大值/最小值放在你要删除的地方,这样你回到那个地方,你就会知道这个地方之前被删除了。 this will decrease the time of deletion (O(1))but it will increase the time of insertion (O(N)), wile you code is based on increasing the time of deletion (O(n)) but it decreases the time of insertion (O(1)) this is your modified code based on shifting on deletion:这将减少删除时间(O(1))但会增加插入时间(O(N)),如果您的代码基于增加删除时间(O(n))但它会减少时间插入(O(1))这是您基于删除转移的修改代码:

#include <stdio.h>
#include <stdlib.h>
int main()
{
   int arr[30];
   int n, i, pos;

   printf("how many ele\n");
   scanf_s("%d", &n);
   printf("enter %d ele\n", n);
   for (i = 0; i < n; i++)
   {
       scanf_s("%d", &arr[i]);
   }

   printf("enter position of element to be deleted\n");
   scanf_s("%d", &pos);
   for (i = pos - 1; i < n - 1; i++)
   {
       arr[i] = arr[i + 1];
   }
   printf("elements in array are\n");
   for (i = 0; i < n; i++)
   {
        printf("%d\t", arr[i]);
   }
   return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM