用C语言编写在一个数组中删除指定元素的程序,以下是本人写的一些代码,由于初学,麻烦高手指点修改

2024-11-08 03:23:11
推荐回答(3个)
回答1:

#include
#define ARR_SIZE 5
int Delete(int *a, int n, int x);

void main()
{
int a[ARR_SIZE-1], x, i, n;

printf("Please enter array numbers:\n");
scanf("%d", &n);

printf("Please enter array:\n");
for (i=0; i {
scanf("%d", &a[i]);
}

printf("Please enter a number what you want to delet:\n");
scanf("%d", &x);

if( Delete(a, n, x) == -1 )
printf("can not find the number!\n") ;
else
{
printf("After delet %d:\n", x);
for(i=0; i < n - 1; i++)
{
printf("%d ", a[i]); // 不要加地址符,我还以为我编译器坏了,囧
}
}
}

int Delete(int *a, int n, int x)
{
int *p=NULL, *pos=NULL;

for (p=a; p {
if (*p == x)
break;
}

if( p >= a + n )
return -1 ;

for( ; p < a + n - 1 ; ++p ) //循环反了,后边的数据会把前边的覆盖
{
*p=*(p+1);
}

return 0 ;
}

回答2:

#include
#define ARR_SIZE 50 //你定义为5,我不太清楚为什么。不过应该定义一个大一些的数。
void Delete(int *a,int n,int x);
void main()
{
int a[ARR_SIZE],x,i,n;
printf("Please enter array numbers:\n");
scanf("%d",&n);
printf("Please enter array:\n");
for (i=0;i scanf("%d",&a[i]);
printf("Please enter a number what you want to delet:\n");
scanf("%d",&x);
Delete(a,n,x);
}

void Delete(int *a,int n,int x)
{
int *p,*pos;
pos=a+n;
for(p=a;p if(*p==x)
{ pos=p;
for(;p<(a+n-1);p++)
*p=*(p+1);
break;
}
if(pos==a+n)
printf("No this number!\n");
printf("After delet %d:\n",x);
for(p=a;p<(a+n-1);p++)
printf("%d ",*p);
}

回答3: